【Node.js】文件流下载

后端把文件以流的形式发送给前端,前端将流转成一个一个的blob文件,将这些 blob 转成url,将url放到a标签上,用于点击,下载文件,处理大型文件和动态生成的文件。

index.js

js 复制代码
import express from 'express'
import cors from 'cors'
import fs from 'fs'
import path from 'path'

const app = express()
app.use(cors())
app.use(express.json())

app.post('/download', (req, res) => {
    const fileName = req.body.fileName
    const filePath = path.join(process.cwd(), 'static', fileName)
    const content = fs.readFileSync(filePath)  // 不加 utf8 配置返回就是一个 buffer 流
    res.setHeader('Content-Type', 'application/octet-stream')  // octet-stream 二进制流
    // Content-Disposition 直接预览而不是下载 默认inline 内联模式
    // 改为 attachment 将文件当做一个附件进行下载
    res.setHeader('Content-Disposition', 'attachment;filename=' + fileName)
    res.send(content)
})

app.listen(3000,()=> {
    console.log('server is running on port 3000')
})

index.html

复制代码
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<button id="btn">download</button>
<script>
    const btn = document.querySelector('#btn')
    btn.addEventListener('click', function () {
        fetch('http://localhost:3000/download',{
            method: 'post',
            body: JSON.stringify({
                fileName: 'cat1.png'
            }),
            headers: {
                'Content-Type': 'application/json'
            }
        }).then(res=>res.arrayBuffer()).then(res=> {
            // 转成 blob
            const blob = new Blob([res], {type: 'image/png'})
            // 转成 url
            const url = URL.createObjectURL(blob)
            // 创建 a 标签挂载 url 模拟点击
            const a = document.createElement('a')
            a.href = url
            a.download = 'cat1.png'
            a.click()
        })
    });
</script>
</body>
</html>
相关推荐
太子釢15 小时前
AI 开发个人记账 App(服务端篇)
node.js·ai编程
用户643404951485118 小时前
Elpis 项目构建工具与前端基建实践总结
node.js
FungLeo19 小时前
成为全栈·Node 后端篇·后端测试策略:单元、集成与测试数据库
单元测试·node.js·集成测试·测试策略·成为全栈·测试数据库
FungLeo19 小时前
成为全栈·Node 后端篇·评论内容安全:敏感词过滤、三态审核与级联删除
node.js·敏感词过滤·成为全栈·评论内容安全·评论审核·级联删除
FungLeo1 天前
成为全栈·Node 后端篇·阅读量防刷:去重、冷却与计数写分离
node.js·读写分离·数据去重·接口防刷·成为全栈·数据冷却
脉动数据行情12 天前
Node.js WebSocket 实现贵金属实时行情监听 伦敦金 / 伦敦银自动重连方案
websocket·node.js·vim
不老刘2 天前
一行命令解决 Node.js 版本兼容问题:`--openssl-legacy-provider` 深度解析
node.js
万敏3 天前
Vue3 全栈实战:第一阶段复盘(第1-8周)
vue.js·node.js·全栈
濮水大叔3 天前
舒服了,CabloyJS 的 AI Spec 驱动开发会自动生成甘特图和燃尽图
typescript·node.js·vibecoding
FungLeo3 天前
成为全栈·Node 后端篇·部署上线:从本地起服到真正对外服务
node.js·后端部署·成为全栈