Node.js实现文件下载

1.设置响应头:

使用 res.writeHead 设置适当的响应头,包括 Content-Type 和 Content-Disposition 以触发下载对话框。
2.创建文件读取流:

使用 fs.createReadStream 创建文件读取流,并通过 pipe 方法将其连接到响应对象 res,从而将文件内容发送给客户端。

javascript 复制代码
const express = require('express');
const path = require('path');
const fs = require("fs");
const router = express.Router();

router.get('/download/example.txt', function(req, res) {
    const filePath = path.join(__dirname, 'example.txt');
    
    // 设置响应头
    res.writeHead(200, {
      'Content-Type': 'application/octet-stream',
      'Content-Disposition': 'attachment; filename="example.txt"'
    });
    
    // 创建文件读取流并将其连接到响应对象
    const fileStream = fs.createReadStream(filePath);
    fileStream.pipe(res);
});
相关推荐
im_AMBER4 小时前
React 16
前端·笔记·学习·react.js·前端框架
02苏_4 小时前
ES6模板字符串
前端·ecmascript·es6
excel4 小时前
⚙️ 一次性警告机制的实现:warnOnce 源码深度解析
前端
excel4 小时前
Vue SFC 样式编译核心机制详解:compileStyle 与 PostCSS 管线设计
前端
excel4 小时前
🧩 使用 Babel + MagicString 实现动态重写 export default 的通用方案
前端
excel4 小时前
Vue SFC 编译器主导出文件解析:模块组织与设计哲学
前端
excel4 小时前
深度解析:Vue SFC 模板编译器核心实现 (compileTemplate)
前端
excel4 小时前
Vue SFC 解析器源码深度解析:从结构设计到源码映射
前端
excel4 小时前
Vue SFC 编译全景总结:从源文件到运行时组件的完整链路
前端
excel4 小时前
Vue SFC 编译核心解析(第 5 篇)——AST 遍历与声明解析:walkDeclaration 系列函数详解
前端