1.总体概述
2 一般来说,前端下载文件有两种方式
3.下面分别介绍这两种方式
3.1 二进制流(分两步走)
function getBinaryFile(url,params){
return axios({
url: url,
method:'post' ,
params,
responseType: 'blob'
})
}
function downFileByBinary(binary,fileName){
let url = URL.createObjectURL(new Blob([binary]))
let link = document.createElement('a')
let event = new MouseEvent("click");
link.style.display = 'none'
link.href = url
link.setAttribute('download',fileName)
link.dispatchEvent(event);
}
getBinaryFile(url,params).then(data=>{
downFileByBinary(data,fileName)
}
)
3.2 文件地址(也是分两步走)
- 有时我们想要通过地址下载图片
- 但是通过
<a href="文件地址" download="fileName">点击下载</a>
- 通过download属性下载,但是有时候翻车了,发现浏览器直接打开了
- 这时候我们只有曲线救国了
通过canvas
- 第一步: 获取文件(图片)地址
- 第二步:通过canvas曲线进行下载
function downImgByCanvas(url,fileName){
let image = new Image();
image.src = url;
image.setAttribute("crossOrigin", "anonymous");
image.onload = function() {
let canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
let context = canvas.getContext("2d");
context.drawImage(image, 0, 0, image.width, image.height);
let url = canvas.toDataURL("image/png");
let a = document.createElement('a')
a.style.display = 'none'
a.href = url
a.setAttribute('download',fileName)
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
};
}