首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Node.js响应中发送文件

Node.js响应中发送文件
EN

Stack Overflow用户
提问于 2012-04-07 00:06:29
回答 3查看 233.1K关注 0票数 131

Expressjs框架有一个sendfile()方法。我如何在不使用整个框架的情况下做到这一点呢?

我正在使用node-native-zip创建一个归档文件,并希望将其发送给用户。

EN

回答 3

Stack Overflow用户

发布于 2021-06-01 15:53:31

这对我很有帮助。一旦你到达/your-route路径,它就会开始下载文件。

代码语言:javascript
复制
app.get("/your-route", (req, res) => {

         let filePath = path.join(__dirname, "youe-file.whatever");

         res.download(filePath);
}

是的,download也是一种快速方法。

票数 3
EN

Stack Overflow用户

发布于 2021-05-08 05:41:26

有点晚了,但是express有一个帮手可以让生活变得更容易。

代码语言:javascript
复制
app.get('/download', function(req, res){
  const file = `${__dirname}/path/to/folder/myfile.mp3`;
  res.download(file); // Set disposition and send it.
});
票数 1
EN

Stack Overflow用户

发布于 2021-11-26 13:18:10

如果您只需要使用Node.js原生文件发送gzipped格式的飞行文件:

代码语言:javascript
复制
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()
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10046039

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档