(Turn) js According url download pictures

The first:

The most convenient way is to use native HTML5 download attribute, this attribute can also be used to download files. E.g:


But clearly, if the download is achieved using the pure HTML attributes for dynamic content, we can not do anything.

Want to achieve does not require the user clicks on the picture can be automatically downloaded to the client can refer to the following method

The second: With achieve base64 download pictures

If we want to download a picture, this picture can be converted to base64 format and download

 var downloadIamge = function(imgsrc, name) { //下载图片地址和图片名
        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;
    }
    downloadIamge("1.jpg", "3.jpg");复制代码

However, this approach has some problems:

  1. Google Chrome can not download anywhere we want on the client computer
  2. 360 download prompt box pops up in your browser
  3. IE11 browser out of the page, directly open the picture, can not be downloaded


Guess you like

Origin blog.csdn.net/weixin_33924770/article/details/91395507