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);
});
相关推荐
用户47949283569151 小时前
claude Fable用不了?把Gpt 5.5pro接到你的claude code里
前端·后端
JieE2121 小时前
LeetCode 101. 对称二叉树|JS 递归 + 迭代双解法,彻底搞懂镜像判断
javascript·算法
冬奇Lab3 小时前
AI Workflow 定义的四次演进:从 Markdown 到 JS 脚本,再到分布式多 Agent
javascript·人工智能·agent
zhangxingchao3 小时前
Kotlin常用的Flow 操作符整理
前端
IT_陈寒5 小时前
React的useState居然还有这种坑?我差点删库跑路
前端·人工智能·后端
Pedantic6 小时前
SwiftUI 手势笔记
前端·后端
橙子家6 小时前
浏览器缓存之【结构化数据库与缓存】: IndexedDB、Cache storage 和 Storage buckets
前端
user20585561518137 小时前
X6 中边悬浮置顶,规避 `mouseleave` 事件丢失问题
前端
李明卫杭州7 小时前
CSS aspect-ratio 属性完全指南
前端