import axios from 'axios' //引入axios
export const download = (fileUrl, name)=> { // 下载文件地址和名称
// console.log(fileUrl, name)
//使用a标签的download属性,下载任意类型的文件、
// {注意:1.解决乱码问题,type指定文件类型
// 2.Blob([res.data]:传入的是res.data;而不是res
// 3.responseType指定为blob对象}
axios({
method: "GET", // "POST"
url: fileUrl,
responseType: "blob", //【重点:设置返回数据类型,这里一定要设置,否则下载下来的文件会是空白】
}).then(res => {
downloadToFile(res,name)
//downloadFileByReader(res,name)
})
}
function downloadToFile(res,fileName){
var downloadUrl = window.URL.createObjectURL(new Blob([res.data],{type:res.data.type}))
var a = document.createElement('a')
a.style.display = 'none'
a.href = downloadUrl
a.download = fileName
//创建一个点击事件,并传递给a
var event = new MouseEvent('click')
a.dispatchEvent(event)
}
// readAsDataURL() 方法会读取指定的 Blob 或 File 对象。读取操作为异步操作,当读取完成时,
//可以从onload回调函数中通过实例对象的result属性获取data:URL格式的字符串(base64编码),
// 此字符串即为读取文件的内容,可以放入a标签的href属性中
function downloadFileByReader(res,fileName){
const reader = new FileReader()
// 传入被读取的blob对象
reader.readAsDataURL(res.data)
// 读取完成的回调事件
reader.onload = (e) => {
let a = document.createElement('a')
a.download = fileName
a.style.display = 'none'
// 生成的base64编码
let url = reader.result
a.href = url
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
}
所有使用a标签下载任意类型文件
最新推荐文章于 2024-04-19 11:25:38 发布