可以解决图片不同源下载问题
<img class="detail-img" v-for="(item,index) in fileList" :src="item.url" :key="index" @click="downloadIamge(item.url,item.name)"/>
<span class="detail-file" v-for="(item,index) in fileList" :key="index" @click="downloadFile(item.url,item.name)">{{item.name}}</span>
/**
* @param imgSrc 图片地址
* @param name 图片名称
*/
downloadIamge(imgSrc, name) {
var image = new Image();
// 解决跨域 Canvas 污染问题
image.setAttribute("crossOrigin", "anonymous");
image.onload = function() {
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext("2d");
context.drawImage(image, 0, 0, image.width, image.height);
var url = canvas.toDataURL("image/png"); //得到图片的base64编码数据
var a = document.createElement("a"); // 生成一个a元素
var event = new MouseEvent("click"); // 创建一个单击事件
a.download = name || "photo"; // 设置图片名称
a.href = url; // 将生成的URL设置为a.href属性
a.dispatchEvent(event); // 触发a的单击事件
};
image.src = imgSrc;
},
/**
* @param src 文件地址
* @param name 文件名称
*/
downloadFile (src, name) {
let x = new XMLHttpRequest();
x.open("GET", src, true);
x.responseType = 'blob';
x.onload = function(e) {
let url = window.URL.createObjectURL(x.response)
let a = document.createElement('a');
a.href = url
a.download = name
a.click()
}
x.send();
},