router.get('/download', function (req, res) { let key = req.query.key; let ua = parser(req.headers['user-agent']); redisClient.get(key, function (err, reply) { if (!reply) { return res.status(404).send('The download link has expired'); } // reply is null when the key is missing let obj = JSON.parse(reply); let filePath = config.download.directory + `${obj.path}`; let filename = obj.filename; //res.download返回头部是双filename,对于Safari支持有问题,所以换流形式
if (['Edge', 'Chrome', 'Firefox'].indexOf(ua.browser.name) > -1) { res.download(filePath, filename, function (err) { if (err) { logger.error('有错误'); logger.error(err) } } ); } else { let mimetype = mime.lookup(filePath); res.setHeader('Content-type', mimetype); if (ua.browser.name == 'IE') { res.setHeader('Content-Disposition', 'attachment; filename=' + encodeURIComponent(filename)); } else { /* safari等其他非主流浏览器*/ res.setHeader('Content-Disposition', 'attachment; filename=' + newBuffer(filename).toString('binary')); } let filestream = fs.createReadStream(filePath); filestream.pipe(res); }