在项目中遇到一个问题,后端传回来的图片可以查看,但是下载时会提示跨域。
再搜索了多种办法下,发现要提前把图片转为base64,在进行下载,就可以成功了。
具体方法如下。
// 下载图片
insertImg (url,name) {
let _this = this
let image = new Image()
image.src = url + '?v=' + Math.random()
image.crossOrigin = "*"
image.onload = function(){
download.download(_this.getBase64Image(image),name);
}
},
// 跨域图片转base64
getBase64Image (img) {
let canvas = document.createElement("canvas")
canvas.width = img.width
canvas.height = img.height
let ctx = canvas.getContext("2d")
ctx.drawImage(img, 0, 0, img.width, img.height)
let dataURL = canvas.toDataURL("image/png")
return dataURL
},
// 下载图片
details(event) {
if (event.files != null) {
this.insertImg(event.files.url, event.files.fileName)
} else {
this.$Message.info("暂无信息");
}
},