闲聊:

问题:项目中的一个bug,使用a标签的href download 的下载功能,但是对于图片 .txt文件,浏览器能解析的文件,会直接展示出来。

征程:看了各种博客,什么乱七八糟的都有(a标签啦,window.open() 等等),最后东拼西凑,终于把图片下载拿下了。

上代码---->

本次项目用的是axios。

具体知识点:

1.手写一个get请求。

2.请求头设置:let header = {'Content-Type': 'multipart/form-data;charset=UTF-8'};//设置content-type

3.设置请求的返回数据类型 responseType: "arraybuffer"。//此处不设置的话,也能下载,但是图片的数据有问题。

4.请求成功之后,把数据放在blob。 let blob = new Blob([res.data], { type: `application/${fileSuffix}`}) // 假设文件为pdf

在这个过程中也看了一些人的博客。相关大佬博客:

1.responseType: "arraybuffer" 灵感来源。https://blog.csdn.net/zj25xy11/article/details/90447122

2.blob 来源。https://segmentfault.com/q/1010000014569305

3.原生写法使用XMLHttpRequest对象https://blog.csdn.net/qq_19313497/article/details/104234723

//html代码

<span @click="downloadFile(item.annex_url,item.fileName)">下载</span> 

//文件下载函数

downloadFile :function (fileUrl,fileName){

//获取远程服务器.md文件数据。

let header = {'Content-Type': 'multipart/form-data;charset=UTF-8'};//设置content-type

this.$axios.get(formUrl.splitUrl(fileUrl),header).then((res)=>{//formUrl.splitUrl(fileUrl)此处是对请求url的格式化。

let fileSuffix = fileUrl.split('.').pop();//文件名后缀。

console.log(fileSuffix)

let blob = new Blob([res.data], { type: `application/${fileSuffix}`}) // 假设文件为pdf

let link = document.createElement('a');

link.href = window.URL.createObjectURL(blob);

link.download = `${fileName}`;

link.click();

link.remove();

});

},

//因为axios是封装的,所以在这里进行了,配置

get(url, header,params){

if(typeof header !== 'undefined'){

return axios({

method: 'get',

url: `${url}`,

headers: header,

responseType: "arraybuffer",

});

}}

代码只是一个对于解决方式的参考,直接粘贴意义不大,不过解决流程应该讲的已经很明白了吧。

如果对你有帮助,请在评论区扣1,如果有问题,请评论上你的问题。

Logo

前往低代码交流专区

更多推荐