当前位置: 首页 > Web前端 > vue.js

下载文件功能

时间:2023-03-31 18:18:07 vue.js

使用a标签的download进行下载。如果是第三方资源,需要请求回来,否则会以链接方式打开。还要检查是否有阻止后端的CORS策略。//判断是否是IE浏览器IEVersion(){letuserAgent=navigator.userAgent;//获取浏览器的userAgent字符串letisIE=userAgent.indexOf("compatible")>-1&&userAgent.indexOf("MSIE")>-1;//判断是否为IE<11浏览器letisEdge=userAgent.indexOf("Edge")>-1&&!isIE;//判断是否IE的Edge浏览器letisIE11=userAgent.indexOf('Trident')>-1&&userAgent.indexOf("rv:11.0")>-1;if(isIE||isEdge||isIE11){returntrue}},download(){constfileName='ITSell.jpeg'//导出文件名//对于标签,只有Firefox和Chrome(内核)支持下载属性//IE10及以上支持blob但仍然不支持下载constblob=newBlob([content])//构造一个blob对象来处理数据。content是请求返回的blob数据;请求时,添加responseType='blob'让服务器返回blob类型if('download'indocument.createElement('a')&&!IEVersion()){//支持带标签的浏览器.createElement('a')//创建标签link.download=fileName//添加属性到标签link.style.display='none'link.href=URL.createObjectURL(blob);document.body.appendChild(link)link.click()//执行下载URL.revokeObjectURL(link.href)//发布urldocument.body.removeChild(link)//发布标签}else{//其他浏览导航器。msSaveBlob(blob,文件名);}},