js, html front-end pc end click to download pictures according to url

Just copy the code below to use it (variables are only imgsrc and file name)

Of course, there are also downloads through the a tag (there is a pit, it is not applicable to the mobile phone, and the a tag can download base64 pictures), so let's see my code
Insert picture description here

This is my code

uploadPoster(imsrc,name) {
    
    
            let imgsrc='https://res.xxxxx.com/adf442a7-1080-4c01-bf3b-f2cewea5f78b6d.png'
            try{
    
    
                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 = name || "photo"; // 设置图片名称
                    a.href = url; // 将生成的URL设置为a.href属性
                    a.dispatchEvent(event); // 触发a的单击事件
                };
                image.src = imgsrc;
        
            }catch(e){
    
    
                console.log(e);
            }
        },

Guess you like

Origin blog.csdn.net/weixin_45629623/article/details/110526520