当前位置: 首页 > Web前端 > JavaScript

js下载文件的实现方法

时间:2023-03-27 00:35:32 JavaScript

供参考,记录平时遇到的问题1.普通下载当后台返回的资源是链接时,可以使用a标签或者window.location.href打开它直接。1.a标签的形式在H5中,a标签添加了下载属性。当点击包含该属性的链接时,浏览器会以下载文件的形式下载href属性上的链接。下载//或包函数download(href,title){consta=document.createElement('a');a.setAttribute('href',href);a.setAttribute('下载',标题);a.click();}download('https://example.com','test')2.window.location.href直接打开window.location.href==='https://example.com'2.流式文件下载当后端返回的文件为流式文件时,以umi-request请求方式为例,首先要在request中包含设置返回类型:responseType:"blob"importrequestfrom"umi-要求”;exportconstdownLoad=(url,fileName)=>request(url,{method:"POST",data:data,responseType:"blob",//以二进制表示一段内存}).then(data)=>{constblob=数据;让link=document.createElement("a");link.href=URL.createObjectURL(newBlob([blob],{type:"application/vnd.ms-excel"}));link.download=文件名;document.body.appendChild(链接);链接.点击();URL.revokeObjectURL(link.href);};1、自定义文件名这时候可以发现后台返回的是一个流文件,而前台收到的是乱码。前端自定义文件名后,直接下载即可。downLoad('https://example.com/api/download','test.xlsx')2.使用后端定义的文件名当使用后端的fileName时,这个当你想得到在后端的内容配置中定义的文件名。先调用接口,发现文件名在请求头的content-disposition中。需要注意的是,我们虽然可以看到,但是获取不到请求头。如果想让浏览器能够访问其他的响应头,需要在后端的服务器上设置Access-Control-Expose-Headers//后端一般写法headers.add("Access-Control-Expose-Headers","内容-处置");这时候可以获取相关信息,发现是编码的,需要decodeURI解码constdisposition=response.headers.get('Content-Disposition');constfileName=decodeURI(disposition.split(";")[1].split("filename=")[1])注意:请求方法中不能直接获取请求头信息,需要拦截请求request.interceptors.response.use(async(response)=>{constdisposition=response.headers.get("Content-Disposition");//获取Content-Dispositionreturndisposition//Content-Disposition有值时处理,让其他请求的响应去?{blob:awaitresponse.blob(),//将二进制数据转换为blob对象,这一步是异步的所以使用async/awaitfileName:decodeURI(disposition.split(";")[1].split("filename=")[1]),//处理Content-Disposition,获取header中的文件名}:response;});完整代码如下:requestfileimportrequestfrom"umi-request";//响应拦截request.interceptors.response.use(async(response)=>{constdisposition=response.headers.get("Content-Disposition");//获取Content-Dispositionreturndisposition//当Content-Disposition中有值时进行处理,让其他请求的response去?{blob:awaitresponse.blob(),//二进制数据转换为blob对象,这一步是异步的所以使用async/awaitfileName:decodeURI(disposition.split(";")[1].split("filename=")[1]),//handleContent-Disposition,Getthefile标题中的名称}:response;});exportconstdownLoadExcel=(url)=>request(url,{method:"POST",data:data,//responseType:"blob",//注释掉这部分}).then(data=>{const{blob,fileName}=response;letlink=document.createElement("a");link.href=URL.createObjectURL(newBlob([blob],{type:"application/vnd.ms-excel"}));link.download=fileName;document.body.appendChild(link);link.click();URL.revokeObjectURL(link.href);document.body.removeChild(link);});reactfile下载js文件异步下载(){awaitdownLoadExcel('http://example.com/api/下载');},