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);
});
相关推荐
前端大卫2 分钟前
H5 渲染 PDF 并添加高亮的两种方案【附源码】
前端
因_崔斯汀1 小时前
用 AI 生成 Three.js 沉浸式网站,代码与 Skill 均已开源
前端·人工智能
葡萄城技术团队1 小时前
一键触发工作表中所有异步函数:用依赖单元格刷新 SpreadJS 公式
前端
Bigger2 小时前
谁动了我的 URL?——记一次微前端"灵异 Bug"的排查实录
前端·ai编程·vue-router
JavaGuide2 小时前
轻量开源版 IDEA 来了!
前端·后端
2601_962097482 小时前
JavaScript 异步编程
javascript·ajax·回调函数·异步编程·子线程
张洪权2 小时前
nest.js websocket 群聊----私聊功能
前端·nestjs
流光D2 小时前
AI Era: Building Web Sites and Configuring Nginx Reverse Proxy Process
前端·人工智能·nginx
sakidd2 小时前
VS Code 的 AI Chat 现在已经这么能干了?
前端
计算机魔术师2 小时前
英伟达砸130亿美元买下一个平台,黄仁勋到底在怕什么?
前端