res.download()
它在路径上传输文件作为“附件”。例如:
var express = require('express'); var router = express.Router(); // ... router.get('/:id/download', function (req, res, next) { var filePath = "/my/file/path/..."; // Or format the path using the `id` rest param var fileName = "report.pdf"; // The default name the browser will use res.download(filePath, fileName); });
对于pdf,Word文档等静态文件,只需在配置中使用Express的静态函数:
// Express config var app = express().configure(function () { this.use('/public', express.static('public')); // <-- This right here });
然后将所有文件放在'public'文件夹中,例如:
/public/docs/my_word_doc.docx
然后一个普通的旧链接将允许用户下载它:
<a href="public/docs/my_word_doc.docx">My Word Doc</a>
我是这样做的:
码:
let fs = require('fs'); let path = require('path'); let myController = (req, res) => { let filename = 'myFile.ext'; let absPath = path.join(__dirname, '/my_files/', filename); let relPath = path.join('./my_files', filename); // path relative to server root fs.writeFile(relPath, 'File content', (err) => { if (err) { console.log(err); } res.download(absPath, (err) => { if (err) { console.log(err); } fs.unlink(relPath, (err) => { if (err) { console.log(err); } console.log('FILE [' + filename + '] REMOVED!'); }); }); }); };
在Express 4.x中,有一个 attachment() 方法 Response :
attachment()
Response
res.attachment(); // Content-Disposition: attachment res.attachment('path/to/logo.png'); // Content-Disposition: attachment; filename="logo.png" // Content-Type: image/png
'use strict'; var express = require('express'); var fs = require('fs'); var compress = require('compression'); var bodyParser = require('body-parser'); var app = express(); app.set('port', 9999); app.use(bodyParser.json({ limit: '1mb' })); app.use(compress()); app.use(function (req, res, next) { req.setTimeout(3600000) res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept,' + Object.keys(req.headers).join()); if (req.method === 'OPTIONS') { res.write(':)'); res.end(); } else next(); }); function readApp(req,res) { var file = req.originalUrl == "/read-android" ? "Android.apk" : "Ios.ipa", filePath = "/home/sony/Documents/docs/"; fs.exists(filePath, function(exists){ if (exists) { res.writeHead(200, { "Content-Type": "application/octet-stream", "Content-Disposition" : "attachment; filename=" + file}); fs.createReadStream(filePath + file).pipe(res); } else { res.writeHead(400, {"Content-Type": "text/plain"}); res.end("ERROR File does NOT Exists.ipa"); } }); } app.get('/read-android', function(req, res) { var u = {"originalUrl":req.originalUrl}; readApp(u,res) }); app.get('/read-ios', function(req, res) { var u = {"originalUrl":req.originalUrl}; readApp(u,res) }); var server = app.listen(app.get('port'), function() { console.log('Express server listening on port ' + server.address().port); });
表达 有一个帮手 为此,让生活更轻松。
app.get('/download', function(req, res){ var file = __dirname + '/upload-folder/dramaticpenguin.MOV'; res.download(file); // Set disposition and send it. });
就您的浏览器而言,文件的名称只是“下载”,因此您需要使用另一个HTTP标头为其提供更多信息。
res.setHeader('Content-disposition', 'attachment; filename=dramaticpenguin.MOV');
您可能还想发送一个像这样的mime类型:
res.setHeader('Content-type', 'video/quicktime');
如果你想要更深入的东西,你可以去。
var path = require('path'); var mime = require('mime'); var fs = require('fs'); app.get('/download', function(req, res){ var file = __dirname + '/upload-folder/dramaticpenguin.MOV'; var filename = path.basename(file); var mimetype = mime.lookup(file); res.setHeader('Content-disposition', 'attachment; filename=' + filename); res.setHeader('Content-type', mimetype); var filestream = fs.createReadStream(file); filestream.pipe(res); });
您可以将标题值设置为您喜欢的任何值。在这种情况下,我使用的是mime类型的库 - 节点哑剧 ,检查文件的mime类型是什么。
另一个需要注意的重要事项是我已经将代码更改为使用readStream。这是一种更好的方法,因为在名称中使用任何带有“Sync”的方法都是不赞成的,因为节点是异步的。