react 前端下载图片方法
/** * 下载图片 */ async openDownload(imgUrl, name) { const link = imgUrl; const files = link.split(‘.‘); const type = files[files.length - 1]; // 初始化 XMLHttpRequest const x = new XMLHttpRequest(); if ([‘jpg‘, ‘png‘, ‘jpeg‘, ‘gif‘].includes(type)) { // 图片 const image = await this.getBase64Image(link); x.open(‘GET‘, image, true); } else { // 非图片 x.open(‘GET‘, link, true); } x.responseType = ‘blob‘; x.onload = function() { const url = window.URL.createObjectURL(x.response); const a = document.createElement(‘a‘); a.href = url; a.download = name || ‘‘; a.click(); }; x.send(); }, /** * 图片转base64 */ getBase64Image(img) { return new Promise((resolve, reject) => { if (!img) { reject(new Error(null)); } const canvas = document.createElement(‘canvas‘); const image = new Image(); image.setAttribute(‘crossOrigin‘, ‘anonymous‘); image.src = `${img}?v=${Math.random()}`; image.onload = () => { canvas.width = image.width; canvas.height = image.height; const ctx = canvas.getContext(‘2d‘); ctx.drawImage(image, 0, 0, image.width, image.height); const ext = image.src .substring(image.src.lastIndexOf(‘.‘) + 1) .toLowerCase(); resolve(canvas.toDataURL(`image/${ext}`)); }; image.error = () => { reject(new Error(null)); }; }); },
原文:https://www.cnblogs.com/hanjc/p/15353116.html