1、使用路径只能下载图片:
downloadByBlob(url,name) {
let image = new Image()
image.setAttribute('crossOrigin', 'anonymous')
image.src = url
image.onload = () => {
let canvas = document.createElement('canvas')
canvas.width = image.width
canvas.height = image.height
let ctx = canvas.getContext('2d')
ctx.drawImage(image, 0, 0, image.width, image.height)
canvas.toBlob((blob) => {
let url = URL.createObjectURL(blob)
this.download(url,name)
// 用完释放URL对象
URL.revokeObjectURL(url)
})
}
}
download(href, name) {
let eleLink = document.createElement('a')
eleLink.download = name
eleLink.href = href
eleLink.click()
eleLink.remove()
},
2、使用路径下载文件(所有文件都可以下载)
let url = window.URL.createObjectURL(new Blob([hreLocal])) //创建下载链接
let link = document.createElement('a') //创建a标签
link.style.display = 'none' //将a标签隐藏
link.href = url //给a标签添加下载链接
// 此处注意,要给a标签添加一个download属性,属性值就是文件名称
否则下载出来的文件是没有属性的,空白白
link.setAttribute('download', name)
document.body.appendChild(link)
link.click()
3、调接口、传参,下载文件:
axios.post(请求路径URL,{参数}),{
responseType:'blob'
}.then((res)=>{
this.handledownloadFiles(下载路径)
})
//type:application/zip为下载压缩包
handledownloadFiles(data) {
//创建下载链接
let url = window.URL.createObjectURL(new Blob([data], {type: 'application/zip'}));
//创建a标签
let link = document.createElement('a');
/将a标签隐藏
link.style.display = 'none';
//给a标签添加下载链接
link.href = url;
// 此处注意,要给a标签添加一个download属性,属性值就是文件名称
否则下载出来的文件是没有属性的,空白白
link.setAttribute('download.txt', " ");
document.body.appendChild(link);
link.click();
},
上面踩坑下载pdf打不开
使用XMLHttpRequest对象
let request = new XMLHttpRequest();
request.responseType = "blob";//定义响应类型
request.open("GET", fileUrl);
request.onload = function () {
let url = window.URL.createObjectURL(this.response);
let a = document.createElement("a");
document.body.appendChild(a);
a.href = url;
a.download = fileName
a.click();
}
request.send();