调用下载图片函数后,点击下载图片,会弹出一个文件夹,根据后端返回photoName自动命名,也可修改,保存后下载到文件夹。
// 下载图片
downloadPhoto = () => {
const { photoName, photoUrl } = this.state;
let image = new Image();
// 解决跨域 Canvas 污染问题
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"); //得到图片的base64编码数据
let a = document.createElement("a"); // 生成一个a元素
let event = new MouseEvent("click"); // 创建一个单击事件
a.download = photoName || "photo"; // 设置图片名称
a.href = url; // 将生成的URL设置为a.href属性
a.dispatchEvent(event); // 触发a的单击事件
};
image.src = photoUrl;
}
弹出另一个页面,可浏览图片。
downloadPhoto = () => {
const { photoUrl } = this.state;
window.location.href = photoUrl;
}
弹出文件夹,可下载图片。
downloadPhoto = () => {
const { photoUrl } = this.state;
let elemIF = document.createElement('iframe');
elemIF.src = photoUrl;
elemIF.style.display = 'none';
document.body.appendChild(elemIF);
}