前端下载文件的方式及跨域下载
前端下载文件的方式及跨域下载
二进制下载
this.$axios({ method: "get", //请求方式 responseType: "blob", //告诉服务器我们需要的响应格式 url: "file/download", //地址 }).then(res => { let url = window.URL.createObjectURL(new Blob([res.data])); //转换为可用URl地址 let link = document.createElement("a"); //创建a标签 link.style.display = "none"; //使之不可见 link.href = url; //赋URL地址 link.setAttribute("download", item.fileName); //设置下载属性、以及文件名 document.body.appendChild(link); //将a标签插至页面中 link.click(); //强制触发a标签事件}
URL 下载
后端返回URL
下载路径,前端直接放置在a
标签的href
属性,并赋予a
标签download
属性。
Download() { let link = document.createElement("a"); //创建a标签 link.style.display = "none"; //使其隐藏 link.href = this.Data.filePath; //赋予文件下载地址 link.setAttribute("download", this.Data.fileName); //设置下载属性 以及文件名 document.body.appendChild(link); //a标签插至页面中 link.click(); //强制触发a标签事件}
跨域下载
在URL
下载方式中,遇到mp4/jpg/png
等浏览可以识别的文件格式时,直接在浏览器中打开了该文件。
download
属性也受同源策略的影响,即非同一端口下不能直接下载第三方文件。
document.querySelector('button').onclick = function () { const xhr = new XMLHttpRequest() xhr.open('GET', 'http://127.0.0.1:9003/1.jpg', true) xhr.responseType = 'blob' xhr.onload = () => { if (xhr.status === 200) { const fileType = xhr.response.type // 文件类型,可以根据此类型设置对应的文件名后缀. const suffix = fileType === 'image/jpeg' ? '.jpg' : '.txt' // 设置文件后缀名 var aEle = document.createElement('a') // 创建a标签 // 字符内容转变成blob地址 blob = new Blob([xhr.response]) aEle.style.display = 'none' document.body.append(aEle) var urlObject = window.URL.createObjectURL(blob) aEle.href = urlObject aEle.download = 'fileName' + suffix // 下载的文件名 aEle.click() document.body.removeChild(aEle) } } xhr.send()}
如果返回的是下载类容
const aEle = document.createElement('a') // 创建a标签blob = new Blob([res.data])aEle.download = fileName // 设置下载文件的文件名aEle.href = URL.createObjectUrl(blob)aEle.click() // 设置点击事件
__EOF__
本文作者:是小梁子吖
本文链接:https://www.cnblogs.com/lwildcat/p/14778188.html