前后端实现下载文件,nodejs

 node

app.post("/downfileTest", (req, res, next) => {
  let filePath = __dirname + "/file/" + "可爱捏.mp4";
  let f = fs.createReadStream(filePath);
  let name = "tes11111111111t.mp4";
  res.header( // 设置前端可访问响应头对应字段
    "Access-Control-Expose-Headers",
    "Other-Data, Your-Custom-Header2"
  );
  res.writeHead(200, {
    "Content-Type": "application/force-download",
    "Content-Disposition": "attachment; filename=" + "test.mp4",
    "Other-Data": name,
  });
  f.pipe(res);
});

前端

let btn = document.querySelector('#btn')
        btn.addEventListener('click', () => {
            fetch('http://127.0.0.1:3000/downfileTest', {
                method: 'post',
                responseType: 'blob'
            }).then(res => {
                let name = res.headers.get('Other-Data')
                return res.blob().then(res => { //异步读取
                    var blob = new Blob([res]);
                    var url = window.URL.createObjectURL(res);
                    var a = document.createElement("a");
                    a.href = url;
                    a.download = name;// 这里指定下载文件的文件名
                    a.click();
                    window.URL.revokeObjectURL(url);
                })
            }).catch(err => {
                console.log(err)
            })
        })

顺便说一下,最好用xhr或者xhr封装,fetch我本身不太熟悉,但是懒得引入,浪费了很多时间😅,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
实现前后端之间的信息互通,可以使用 Protocol Buffers(简称 Protobuf)结合 Node.js 来实现。 首先,确保你已经安装了 Node.js 和 Protobuf 的相关依赖。 1. 定义消息格式:在一个 `.proto` 文件中定义消息的格式,该文件描述了前后端之间通信的数据结构。例如,创建一个名为 `message.proto` 的文件,其中包含以下内容: ``` syntax = "proto3"; message Message { string content = 1; } ``` 2. 在前端后端分别生成消息代码:使用 Protobuf 编译器将 `.proto` 文件编译成对应的代码。在终端中运行以下命令: ``` protoc --js_out=import_style=commonjs,binary:./path/to/output/frontend message.proto protoc --js_out=import_style=commonjs,binary:./path/to/output/backend message.proto ``` 这将生成两个文件:`message_pb.js` 和 `message_pb.d.ts`,分别用于前端后端。 3. 在前端后端使用生成的代码:在前端后端的代码中导入生成的代码文件以使用消息类型。例如,在 Node.js 中,可以这样导入和使用消息类型: ```javascript const { Message } = require('./path/to/output/backend/message_pb'); // 创建消息 const message = new Message(); message.setContent('Hello, world!'); // 将消息序列化为字节数组 const bytes = message.serializeBinary(); // 在网络上发送字节数组... // 在后端接收到字节数组后,可以反序列化为消息类型 const receivedMessage = Message.deserializeBinary(bytes); // 在后端获取消息内容 const content = receivedMessage.getContent(); console.log(content); // 输出 'Hello, world!' ``` 4. 在前后端之间通过网络传递字节数组:将前端序列化后的字节数组发送到后端,并在后端将字节数组反序列化为消息类型。 使用 Protocol Buffers 可以方便地定义和传输结构化数据,而且具有跨语言和跨平台的特性,适用于前后端之间的数据交换。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值