Expressjs框架有一个sendfile()
方法。我如何在不使用整个框架的情况下做到这一点呢?
我正在使用node-native-zip创建一个归档文件,并希望将其发送给用户。
发布于 2021-06-01 15:53:31
这对我很有帮助。一旦你到达/your-route
路径,它就会开始下载文件。
app.get("/your-route", (req, res) => {
let filePath = path.join(__dirname, "youe-file.whatever");
res.download(filePath);
}
是的,download
也是一种快速方法。
发布于 2021-05-08 05:41:26
有点晚了,但是express有一个帮手可以让生活变得更容易。
app.get('/download', function(req, res){
const file = `${__dirname}/path/to/folder/myfile.mp3`;
res.download(file); // Set disposition and send it.
});
发布于 2021-11-26 13:18:10
如果您只需要使用Node.js原生文件发送gzipped格式的飞行文件:
const fs = require('fs') // Node.js module
const zlib = require('zlib') // Node.js module as well
let sendGzip = (filePath, response) => {
let headers = {
'Connection': 'close', // intention
'Content-Encoding': 'gzip',
// add some headers like Content-Type, Cache-Control, Last-Modified, ETag, X-Powered-By
}
let file = fs.readFileSync(filePath) // sync is for readability
let gzip = zlib.gzipSync(file) // is instance of Uint8Array
headers['Content-Length'] = gzip.length // not the file's size!!!
response.writeHead(200, headers)
let chunkLimit = 16 * 1024 // some clients choke on huge responses
let chunkCount = Math.ceil(gzip.length / chunkLimit)
for (let i = 0; i < chunkCount; i++) {
if (chunkCount > 1) {
let chunk = gzip.slice(i * chunkLimit, (i + 1) * chunkLimit)
response.write(chunk)
} else {
response.write(gzip)
}
}
response.end()
}
https://stackoverflow.com/questions/10046039
复制相似问题