【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>
相关推荐
贩卖纯净水.2 小时前
Webpack的基本使用 - babel
前端·webpack·node.js
贩卖纯净水.3 小时前
Webpack依赖
前端·webpack·node.js
笑醉踏歌行6 小时前
NVM,Node.Js 管理工具
运维·ubuntu·node.js
chxii8 小时前
1.4 Node.js 的 TCP 和 UDP
node.js
xd0000221 小时前
11. vue pinia 和react redux、jotai对比
node.js
程序猿小D1 天前
第16节 Node.js 文件系统
linux·服务器·前端·node.js·编辑器·vim
前端老六喔1 天前
🎉 开源项目推荐 | 让你的 TypeScript/React 项目瘦身更简单!
node.js·前端工程化
醉书生ꦿ℘゜এ1 天前
npm error Cannot read properties of null (reading ‘matches‘)
前端·npm·node.js
超级土豆粉1 天前
从0到1写一个适用于Node.js的User Agent生成库
linux·ubuntu·node.js
空中湖1 天前
‘pnpm‘ 不是内部或外部命令,也不是可运行的程序
npm·node.js