首页 > 其他 > 详细

react 前端下载图片方法

时间:2022-05-27 21:22:52      阅读:12      评论:0      收藏:0      [点我收藏+]
/**
 * 下载图片
 */
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));
        };
    });
},

 

react 前端下载图片方法

原文:https://www.cnblogs.com/hanjc/p/15353116.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!