谈谈关于文件下载

昨天跟后端小哥调了调关于文件下载的接口,还是有一些坑的,这里总结一下。

我们分为后端返回二进制流或者返回 url 的形式进行讲述。

一、后端返回二进制流

总的来说关于文件下载前端有以下两种方法去拉取数据:

  1. window.open 方法
  2. ajax 方法

此时后端返回的都是二进制流。

请添加图片描述

1. window.open 方法

格式为:window.open(url)

传输数据量不多的时候采用 window.open, 而此时浏览器是采用 get 方法传输数据的。

后端同学设置返回的响应头为 Content-Type: text/csv 或者

Content-Type: application/octet-stream

content-disposition: attachment; filename=order_list.xlsx

2. ajax 方法

如果浏览器端需要传输数据量很多的时候,我们采用 post 方法去请求,这时候需要用到 ajax 去异步拉取数据的,在数据返回的时候执行下载的操作。

此时我们需要设置 ajax 的 responseType 为 blob,请求举例

const exportAllOrder = (model: any = {}) => {
  return axios({
    method: 'POST',
    url: [url],
    data: [data],
    responseType: 'blob',
    withCredentials: true,
  });
};

const res = await exportAll(model);
const blob = new Blob([res.data]);
const fileName = 'order.xlsx';
const link = document.createElement('a');
link.download = fileName;
link.style.display = 'none';
link.href = URL.createObjectURL(blob); // 这里是将文件流转化为一个文件地址
document.body.appendChild(link);
link.click();
URL.revokeObjectURL(link.href); // 释放URL 对象
document.body.removeChild(link);

后端同学设置返回的响应头为

Content-Type: application/octet-stream

content-disposition: attachment; filename=order_list.xlsx

如果需要前端拿取后端的文件名,解析出 content-disposition 的文件名即可。

二、后端返回 url

window.open 就没什么好说的了,看看 ajax 应该怎么处理。

const url = await exportAll(model);
const fileName = 'order.xlsx';
const link = document.createElement('a');
link.download = fileName;
link.style.display = 'none';
link.href = url;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

版权声明:本文为suedar1原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。