【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>
相关推荐
集成显卡10 小时前
基于 Node.js 的 API 方式接入深度求索Deepseek、字节跳动豆包大模型
前端·人工智能·node.js
HexCIer11 小时前
cbT.js: 一个让模板继承变得优雅的 Node.js 模板引擎
javascript·node.js
Q_Q51100828514 小时前
python的小学课外综合管理系统
开发语言·spring boot·python·django·flask·node.js
ChongYu重玉16 小时前
【node/vue】css制作可3D旋转倾斜的图片,朝向鼠标
javascript·css·vue.js·经验分享·笔记·node.js·vue
前端双越老师17 小时前
使用 langChain.js 实现 RAG 知识库语义搜索
人工智能·langchain·node.js
植物昂光17 小时前
基于Node.js的微博热榜抓取与展示开发记录
前端·node.js
今天也在写bug18 小时前
输入npm install后发生了什么
前端·npm·node.js
popoxf1 天前
在新版本的微信开发者工具中使用npm包
前端·npm·node.js
Q_Q19632884751 天前
python的平安驾校管理系统
开发语言·spring boot·python·django·flask·node.js·php
GISer_Jing1 天前
LLM对话框项目总结II
前端·javascript·node.js