Node.js发送文件作为响应

Expressjs框架具有sendfile()方法。我如何在不使用整个框架的情况下做到这一点。我正在使用node-native-zip创建档案,并将其发送给用户。



偶然的你
浏览 835回答 3
3回答

jeck猫

您需要使用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 = [文件名]”指定将要下载的文件名。

holdtom

“流”是指“在读取文件数据时将其发送到连接”,而不是“读取内存中的整个文件然后立即将所有数据发送到该连接”(这是典型的幼稚方法)。我的意思不是 “从内存流式传输数据而不将其传输到磁盘”。
打开App,查看更多内容
随时随地看视频慕课网APP