NodeJS CSV导出文件名和内容乱码解决

// 解决不同浏览器下载文件名称乱码
var userAgent = (req.headers['user-agent']||'').toLowerCase();
res.set('Content-Type', 'application/octet-stream;charset=utf-8');

if(userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
    res.setHeader('Content-Disposition', 'attachment; filename=' + encodeURIComponent(filename));
} else if(userAgent.indexOf('firefox') >= 0) {
    res.setHeader('Content-Disposition', 'attachment; filename*="utf8\'\'' + encodeURIComponent(filename)+'"');
} else {
    res.setHeader('Content-Disposition', 'attachment; filename=' + new Buffer(filename).toString('binary'));
}

// 解决excel打开内容乱码
var dataBuffer = Buffer.concat([new Buffer('\xEF\xBB\xBF', 'binary'), new Buffer(data)]);
res.send(dataBuffer);

原文地址:http://imziv.com/blog/article/read.htm?id=55

posted @ 2014-11-04 22:33  Ziv小威  阅读(3620)  评论(0编辑  收藏  举报