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);
});
相关推荐
KaMeidebaby7 小时前
卡梅德生物技术快报|PD1 单克隆抗体定制配套 N 糖全谱质控开发
前端·人工智能·算法·数据挖掘·数据分析
nuIl8 小时前
实现一个 Coding Agent(3):工具调用
前端·agent·cursor
nuIl8 小时前
实现一个 Coding Agent(4):ReAct 循环
前端·agent·cursor
nuIl8 小时前
实现一个 Coding Agent(1):一次 LLM 调用
前端·agent·cursor
nuIl8 小时前
实现一个 Coding Agent(2):让 LLM 流式响应
前端·agent·cursor
copyer_xyf8 小时前
Python 异常处理
前端·后端·python
sugar__salt8 小时前
从栈队列数据结构到JS原型面向对象全解
前端·javascript·数据结构
MageGojo9 小时前
随机文案模块怎么做?从接口封装到前端展示的完整实现思路
javascript·前端开发·api接口·后端开发·随机文案
独特的螺狮粉9 小时前
篮球集训班器具管理系统 - 鸿蒙PC Electron框架完整技术实现指南
前端·javascript·华为·electron·前端框架·开源·鸿蒙
小妖6669 小时前
js 生成随机数技巧 Math.random().toString(36)
javascript·随机数