为了账号安全,请及时绑定邮箱和手机立即绑定

Node.js发送文件作为响应

Node.js发送文件作为响应

偶然的你 2019-11-11 14:14:24
Expressjs框架具有sendfile()方法。我如何在不使用整个框架的情况下做到这一点。我正在使用node-native-zip创建档案,并将其发送给用户。
查看完整描述

3 回答

?
jeck猫

TA贡献1909条经验 获得超7个赞

您需要使用Stream在响应中发送文件(存档),此外,您还必须在响应头中使用适当的Content-type。


有一个执行此操作的示例函数:


const fs = require('fs');


// Where fileName is name of the file and response is Node.js Reponse. 

responseFile = (fileName, response) => {

  const filePath =  "/path/to/archive.rar" // or any file format


  // Check if file specified by the filePath exists 

  fs.exists(filePath, function(exists){

      if (exists) {     

        // Content-type is very interesting part that guarantee that

        // Web browser will handle response in an appropriate manner.

        response.writeHead(200, {

          "Content-Type": "application/octet-stream",

          "Content-Disposition": "attachment; filename=" + fileName

        });

        fs.createReadStream(filePath).pipe(response);

      } else {

        response.writeHead(400, {"Content-Type": "text/plain"});

        response.end("ERROR File does not exist");

      }

    });

  }

}

Content-Type字段的目的是充分描述主体中包含的数据,以使接收用户的代理可以选择适当的代理或机制,以将数据呈现给用户,或者以适当的方式处理数据。


“应用程序/八位字节流”在RFC 2046中定义为“任意二进制数据”,此内容类型的目的是保存到磁盘-这是您真正需要的。


“ filename = [文件名]”指定将要下载的文件名。


查看完整回答
反对 回复 2019-11-11
?
holdtom

TA贡献1805条经验 获得超10个赞

“流”是指“在读取文件数据时将其发送到连接”,而不是“读取内存中的整个文件然后立即将所有数据发送到该连接”(这是典型的幼稚方法)。我的意思不是 “从内存流式传输数据而不将其传输到磁盘”。

查看完整回答
反对 回复 2019-11-11
  • 3 回答
  • 0 关注
  • 827 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信