点击按钮下载图片功能封装,带uuid唯一标识
import { v4 as uuidv4 } from "uuid";
export const downloadPic = (imgUrl) => {
const uuid = uuidv4();
const extension = getImageExtension(imgUrl);
const xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", imgUrl, true);
xmlHttp.responseType = "blob";
xmlHttp.onload = function () {
if (this.status == 200) {
const blob = this.response;
const a = document.createElement("a");
a.id = "downloadPic";
a.href = window.URL.createObjectURL(blob);
a.download = `${uuid + "." + extension}`;
document.body.appendChild(a);
a.click();
const elementToDelete = document.getElementById("downloadPic");
elementToDelete.parentNode.removeChild(elementToDelete);
}
};
xmlHttp.send();
};
function getImageExtension(url) {
var parts = url.split(".");
return parts[parts.length - 1];
}