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);
});
相关推荐
七牛云行业应用12 小时前
别每次重复配置了!CLAUDE.md + Hooks 让 Claude Code 开箱就记住你的规则
前端
超人气王13 小时前
新手学前端 JavaScript 类型判断:一篇彻底搞懂 typeof、instanceof 和 Object.prototype.toString
前端·javascript
LucianaiB13 小时前
耗时30天,DocPilot Qwen正式开源:一个免费无广的开源文档 AI 助手
前端·后端
xiaoshuaishuai813 小时前
C# AvaloniaUI 资源找不到报错
java·服务器·前端·windows·c#
丷丩13 小时前
MapLibre GL JS第35课:显示带地形高程(三维地形)的卫星影像
javascript·gis·map·mapbox·maplibre gl js
How_doyou_do13 小时前
26字节工程营-前端-自我总结
前端
三乐22813 小时前
node不认识类型?多半是没用上这几段代码
javascript
十有八七13 小时前
🧩 组件库死亡倒计时?—— AI 编码冲击下的前端基础设施重构
前端·人工智能
风止何安啊13 小时前
我一个前端仔,居然用 Python 搞起了 AI?从零到一,撸了个 AI 聊天框小 demo
前端·人工智能·后端
GISer_Jing13 小时前
Claude Code插件系统全解析
前端·人工智能·ai·架构