下载图片格式的
/**
* imageUrl: 要下载的图片地址
* name: 下载后的图片名称
*/
export function downloadImage(imageUrl, name){
console.log("====")
const image = new Image();
// 解决跨域 Canvas 污染问题
image.setAttribute('crossOrigin', 'anonymous');
image.onload = function () {
const canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
const context = canvas.getContext('2d');
context.drawImage(image, 0, 0, image.width, image.height);
// 得到图片的base64编码数据
const url = canvas.toDataURL('image/png');
// 生成一个a元素
const a = document.createElement('a');
// 创建一个单击事件
const event = new MouseEvent('click');
a.download = name;
// 将生成的URL设置为a.href属性
a.href = url;
// 触发a的单击事件
a.dispatchEvent(event);
};
image.src = imageUrl;
}
// 下载pdf
/**
* _fileUri: 要下载地址
* name: 下载后的图片名称
*/
export function downloadFileForm(_fileUri,name) {
// window.location.href=url;
let xhr = new XMLHttpRequest();
xhr.open('get', _fileUri, true);
xhr.responseType = 'blob';
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
if (typeof window.chrome !== 'undefined') {
// Chrome version
let link = document.createElement('a');
link.href = window.URL.createObjectURL(xhr.response);
link.download = name;
link.click();
} else if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE version
let blob = new Blob([xhr.response], { type: 'application/pdf' });
window.navigator.msSaveBlob(blob, name);
} else {
// Firefox version
let file = new File([req.response], name, { type: 'application/force-download' });
window.open(URL.createObjectURL(file));
}
}
};
xhr.send();
}