var tarpath='/opt/storage/test.mp4';
var title='测试下载.mp4';
if (fs.existsSync(tarpath)) {
var stream = fs.createReadStream(tarpath);
var userAgent = (req.headers['user-agent']||'').toLowerCase();
if(userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
/*谷歌和IE浏览器下载*/
res.writeHead(200, {
'Content-Type': 'application/force-download;charset=utf-8',
'Content-Disposition': 'attachment; filename='+encodeURIComponent(ret.title)+'.swp'
});
} else if(userAgent.indexOf('firefox') >= 0) {
/*火狐浏览器下载*/
res.writeHead(200, {
'Content-Type': 'application/force-download;charset=utf-8',
'Content-Disposition': 'attachment; filename*="utf8\'\'' + encodeURIComponent(title)+'"'
});
} else {
/* safari等其他非主流浏览器只能自求多福了 */
res.writeHead(200, {
'Content-Type': 'application/force-download;charset=utf-8',
'Content-Disposition': 'attachment; filename=' + new Buffer(title).toString('binary')
});
}
stream.pipe(res);
stream.on('end',function(){
//下载成功后删除源文件
fs.unlink(tarpath)
});
}else{
res.json({success:false,error:'file not exit'});
}
node后台文件下载浏览器兼容处理
最新推荐文章于 2024-07-11 15:17:16 发布