js获取后端返回文件流下载文件至本地 / 通过访问指定路径直接从服务器下载文件

本文介绍了如何使用JavaScript处理后端返回的文件流进行本地下载,设置responseType为'blob'。同时,讲解了利用a标签直接从服务器或前端项目的public/data(vue-cli3)或static(vue-cli2)目录下载文件的方法,以及如何通过window.location下载服务器上的文件。
摘要由CSDN通过智能技术生成

获取后端返回文件流下载文件至本地

responseType: ‘blob’ 注意设置类型为blob

// responseType: 'blob'注意请求类型为blob
exportCheckBill(obj)
        .then(response => {
   
          // 处理请求返回的文件流
          const content = response;
          const blob = new Blob([content]);
          const fileName = `文件名.xlsx`;
          if ("download" 
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
一般来说,可以通过 HTTP POST 请求文件传输到后端。在请求中需要指定文件类型和文件内容。具体实现步骤如下: 1. 创建一个表单,添加一个 input 元素用于选择文件,以及一个 submit 按钮用于提交表单。 ```html <form method="post" enctype="multipart/form-data"> <input type="file" name="file"> <button type="submit">上传文件</button> </form> ``` 2. 当用户点击提交按钮时,浏览器会将表单中的数据封装成一个 HTTP POST 请求,并将请求发送到后端。 3. 后端接收到请求后,从请求体中获取文件内容,并将其保存到指定的本地路径中。 下面是一个使用Node.js实现的文件上传的示例代码: ```javascript const http = require('http'); const formidable = require('formidable'); const fs = require('fs'); http.createServer(function(req, res) { if (req.url == '/upload' && req.method.toLowerCase() == 'post') { // 创建表单解析器 const form = new formidable.IncomingForm(); // 设置上传目录 form.uploadDir = './uploads'; // 解析表单数据 form.parse(req, function(err, fields, files) { // 获取上传的文件 const file = files.file; // 将文件从临时目录移动到上传目录 fs.rename(file.path, form.uploadDir + '/' + file.name, function(err) { if (err) throw err; res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('文件上传成功!'); res.end(); }); }); } else { res.writeHead(200, {'Content-Type': 'text/html'}); res.write('<form method="post" enctype="multipart/form-data">'); res.write('<input type="file" name="file"><br>'); res.write('<button type="submit">上传文件</button>'); res.write('</form>'); res.end(); } }).listen(8080); ``` 这个示例实现了一个简单的 HTTP 服务器,当用户访问路径时,服务器返回一个包含文件上传表单的页面。当用户选择文件并点击提交按钮时,浏览器会将文件上传到服务器,并将文件保存到指定的本地路径中。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值