我的访问者可以访问的网址会触发即时文件下载:
http://localhost:3000/download
以下是此路线的Node.js Express代码:
router.get('/download', function(req, res, next){
res.setHeader('Content-disposition', 'attachment; filename=downloadfile.zip');
res.setHeader('Content-type', 'application/zip');
var filestream = fs.createReadStream('downloadfile.zip');
filestream.pipe(res);
});
所以我正确设置我的标题并提供文件供下载。在Chrome中,如果我使用JavaScript来触发此下载:
window.location.href="/download";
然后Chrome的控制台发出警告:
Resource interpreted as Document but transferred with MIME type application/zip: "http://localhost:3000/download".
然而,文件正确下载。只是警告出现了。这个警告有很多主题,一切似乎都指向确保标题设置正确。我很确定我的是正确的。
以下是回复标题:
HTTP/1.1 200 OK
X-Powered-By: Express
Content-disposition: attachment; filename=downloadfile.zip
Content-type: application/zip
Date: Wed, 23 Dec 2015 19:14:47 GMT
Connection: keep-alive
Transfer-Encoding: chunked
以下是请求标题:
GET /download HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Linux; Android 5.1.1; Nexus 6 Build/LYZ28E) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.20 Mobile Safari/537.36
Referer: http://localhost:3000/filerequest
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,es;q=0.6
Cookie: dwanonymous_259c8c42aa11d4ff581f55a1b8d75159=ablFleC64VDwlUxLnzJvjesSKP; s_fid=3E452B78AEFE8958-0900CA102BA80FF0; com.somthing.iMAWwwee=36335a074-9eds-cbbc-91a4-4b8d238ddw6d6
我在Firefox中没有看到此错误。在Chrome中,我看到此错误,无论我是否有"在下载之前询问保存每个文件的位置"是否在“设置”中选中。
这只是一个警告,我应该期望访问者忽略,或者我可以添加到响应标头中以防止这种情况发生吗?
答案 0 :(得分:0)
您是否尝试过添加Content-Length
标题?
router.get('/download', function(req, res, next){
var stat = fs.statSync('downloadfile.zip');
res.writeHead(200, {
'Content-disposition' : 'attachment; filename=downloadfile.zip'
'Content-Type' : 'application/zip',
'Content-Length' : stat.size
});
var filestream = fs.createReadStream('downloadfile.zip');
filestream.pipe(res);
});