node 文件下载到本地 (支持中文文件名)

downloadfile:function(req,res,next){
var name= encodeURI(req.query.name);

var path= req.query.url;
var url = p.urlprestatic.substr(0, p.urlprestatic.indexOf("/supplierplatformstatic/")+"/supplierplatformstatic/".length)
if(utils.isEmpty(name) || utils.isEmpty(path) || name == undefined || path == undefined){
res.send("<html><head><title>文件下载</title></head><body><script>alert(\"文件名或文件路径不能为空!\");" +
"window.location.href='"+url+"'</script></body></html>")
}else{
try {
var filename = path.substr(path.indexOf("/file")+"/file/".length,path.length)
var filePath = p.targetDir+ filename;
var stats = fs.statSync(filePath);
if(stats.isFile()){
res.set({
'Content-Type': 'application/octet-stream',
'Content-Disposition':"attachment; filename*=UTF-8''"+name,
'Content-Length': stats.size
});
fs.createReadStream(filePath).pipe(res);
} else {

res.send("<html><head><title>文件下载</title></head><body><script>alert(\"文件下载失败!\");" +
"window.location.href='"+url+"'</script></body></html>")
}
}catch(e){
res.send("<html><head><title>文件下载</title></head><body><script>alert(\"文件下载失败!\");" +
"window.location.href='"+url+"'</script></body></html>")
}


}

}

 

posted @ 2018-06-05 14:00  阿泽的小码园  阅读(718)  评论(1)    收藏  举报