首页
Javascript
Html
Css
Node.js
Electron
移动开发
小程序
工具类
服务端
浏览器相关
前端收藏
其他
关于
公司注册

axios二进制文件下载的问题

2020年12月03日 发布 阅读(2264) 作者:Jerman

首先确定下载头是这个样子


使用了content-disposition

content-disposition: attachment; filename="screenshot.png"

解决办法:

1、设置responseTypeblob类型

  1. export const getScreenshot = params => {
  2. return axios({
  3. method: 'get',
  4. url: '/api/screenshot', // 请求地址
  5. params,
  6. responseType: 'blob', // 设置接收格式为blob格式
  7. });
  8. };

2、axios拦截文件下载

  1. axios.interceptors.response.use(
  2. response => {
  3. // 判断文件是否为导出(下载到电脑)
  4. const headers = response.headers;
  5. if (headers['content-disposition']) {
  6. const contentDisposition = response.headers['content-disposition'];
  7. let fileName = `test_${new Date().getTime()}.csv`;
  8. if (/filename=/.test(contentDisposition)) {
  9. fileName = contentDisposition.split('filename=')[1].replace(/"/g, '');
  10. }
  11. // blob类型
  12. let blobType = 'application/octet-stream';
  13. if (/\.png/gi.test(fileName)) {
  14. blobType = 'image/png';
  15. }
  16. const myBlob = new Blob([response.data], { type: blobType });
  17. // 下载
  18. createDownloadUrl(myBlob, fileName);
  19. return response.data;
  20. }
  21. }
  22. )

上面特别要注意的,new Blob第一个参数是一个数组对象

createDownloadUrl下载方法,实际上就创建了一个A链接,设置了download属性

  1. function createDownloadUrl(blob, fileName) {
  2. if (typeof window.navigator.msSaveBlob !== 'undefined') {
  3. // 兼容IE,window.navigator.msSaveBlob:以本地方式保存文件
  4. window.navigator.msSaveBlob(blob, decodeURI(fileName));
  5. } else {
  6. // 创建新的URL并指向File对象或者Blob对象的地址
  7. const blobURL = window.URL.createObjectURL(blob);
  8. // 创建a标签,用于跳转至下载链接
  9. const tempLink = document.createElement('a');
  10. tempLink.href = blobURL;
  11. tempLink.setAttribute('download', fileName);
  12. // 兼容:某些浏览器不支持HTML5的download属性
  13. if (typeof tempLink.download === 'undefined') {
  14. tempLink.setAttribute('target', '_blank');
  15. }
  16. tempLink.style.display = 'none';
  17. // 挂载a标签
  18. document.body.appendChild(tempLink);
  19. tempLink.click();
  20. document.body.removeChild(tempLink);
  21. // 释放blob URL地址
  22. window.URL.revokeObjectURL(blobURL);
  23. }
  24. }
版权声明:本站文章除特别声明外,均采用署名-非商业性使用-禁止演绎 4.0 国际 许可协议,如需转载,请注明出处