当前位置:   article > 正文

Node.js实现文件下载

Node.js实现文件下载

1.设置响应头:
使用 res.writeHead 设置适当的响应头,包括 Content-Type 和 Content-Disposition 以触发下载对话框。
2.创建文件读取流:
使用 fs.createReadStream 创建文件读取流,并通过 pipe 方法将其连接到响应对象 res,从而将文件内容发送给客户端。

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);
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/844874
推荐阅读
相关标签
  

闽ICP备14008679号