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);
});
相关推荐
吃好睡好便好3 小时前
在Matlab中用sphere( )函数绘制球面图
开发语言·前端·javascript·学习·算法·matlab·信息可视化
黑贝是条狗3 小时前
注册表破解chrome,edge阻止浏览器连接本地websocket
前端·javascript·数据库
UXbot3 小时前
AI 原型工具对比(2026):从文字描述到完整 App 界面的 5 款主流平台评测
android·前端·ios·交互·软件构建
ZC跨境爬虫3 小时前
跟着 MDN 学 HTML day_53:(深入理解 XPathResult 接口)
前端·javascript·ui·html·音视频
摸鱼仙人~3 小时前
html-anything 仓库全面介绍
前端·html
之歆3 小时前
DAY_24JavaScript 面向对象深度全解:Object、构造函数与 this 系统指南(上)
开发语言·前端·javascript·原型模式
梦梦代码精3 小时前
开源智能体平台 BuildingAI 深度解析:Monorepo 架构、MCP 集成及 GPT-Image-2 接入实测
前端·人工智能·后端·gpt·开源·github
Asurplus3 小时前
【VUE】17、使用JSEncrypt对数据加解密
javascript·vue.js·jsencrypt·rsa
fanzhonghong3 小时前
javaWeb开发之前端实战(Tlias案例-部门管理)
前端·后端·web·前后端分离
广州华水科技3 小时前
2026年高口碑GNSS变形监测一体机推荐:提升水库安全解决方案
前端