vue中使用文件流进行下载、Blob的使用

我这里只是简单的记录了下载的用法,需要上传功能的话可以看文章下面的链接,里面有Blob更详细的用法

封装方法

function getExel(url, params) {
  // 注意:responseType应设置为:'arraybuffer' or 'blob'
return new Promise(function(resolve, reject) { let data = { method: "GET", url:url, headers: { 'token': gettoken("token") }, responseType: 'arraybuffer' } resolve(axios(data)); }) }

发送请求($Api已经挂载在了vue对象上,所以可以这么使用)

(关于因为Blob对象中的type属性通常是 MIME 类型,所以这里给大家一个链接可以找对应文件的MIME类型:https://www.w3school.com.cn/media/media_mimeref.asp)

this.$Api.getExel("/goodsCheckService/v1/planMaterial/export?idList="+idArray)
          .then(response => {
              let a = document.createElement('a');
 
              //ArrayBuffer 转为 Blob
              let blob = new Blob([response.data], {type: "application/vnd.ms-excel"}); 
              
              let objectUrl = URL.createObjectURL(blob);
              a.setAttribute("href",objectUrl);
              a.setAttribute("download", 'template.xls');
              a.click();
});

(注:以上内容参考链接:https://blog.csdn.net/qq_37899792/article/details/90748268

关于Blob更详细的用法:https://blog.csdn.net/z591102/article/details/107530381

(一位网友写的,觉得很不错,推荐给有需要的小伙伴)

原文地址:https://www.cnblogs.com/jadening/p/14014637.html