vue项目文件下载前端处理


文件下载通常有以下几种方法 
1.通过url下载 
2.通过地址跳转location.href 下载
3.通过提交form表单下载
4. a.download结合blob对象进行下载

本篇主要写第四种方法:

前端接收后台传过来的文件流,请求后台接口时会在请求头加上{responseType:‘blob’}.

具体实现直接上代码:

this.$axios.get(url, {responseType: 'blob'},{
   headers: {'content-type': 'application/x-www-form-urlencoded'}
}).then((response) => {
   let blob = new Blob([response.data]);
   let fileName = row.filename;
   let elink = document.createElement('a');
   elink.download = fileName;
   elink.style.display = 'none';
   elink.target = "_blank";
   elink.href = URL.createObjectURL(blob);
   document.body.appendChild(elink);
   elink.click();
   URL.revokeObjectURL(elink.href); // 释放URL对象
   document.body.removeChild(elink);
 });

谷歌浏览器会自动下载

 

你可能感兴趣的:(vue项目文件下载前端处理)