Bootstrap

JavaScript实现图片下载

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片下载</title>
</head>
<style>
    div {
        width: 30vw;
        margin: 3rem auto;
        text-align: center;
        border: 1px dashed #555;
    }

    img,
    video {
        width: 100%;
    }
</style>

<body>
    <div>
        <img
            src="https://img-blog.csdnimg.cn/534762daa9654b61a89b341a7a82e123.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5LqU6Iqx5ryP,size_20,color_FFFFFF,t_70,g_se,x_16#pic_center">
        <br />
        <button onclick="downloadIamge(imgUrl)">下载图片-方法1</button>
    </div>
    <div>
        <img
            src="https://img-blog.csdnimg.cn/534762daa9654b61a89b341a7a82e123.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5LqU6Iqx5ryP,size_20,color_FFFFFF,t_70,g_se,x_16#pic_center">
        <br />
        <button onclick="downloadUrlFile(imgUrl)">下载图片-方法2</button>
    </div>

    <!-- <div>
        <img
            src="https://img-blog.csdnimg.cn/534762daa9654b61a89b341a7a82e123.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5LqU6Iqx5ryP,size_20,color_FFFFFF,t_70,g_se,x_16#pic_center">
        <br />
        <button class="downloadBtn" type="button" οnclick="downloadImg(imgUrl)">下载图片-方法3</button>
    </div>

    <div>
        <h4>通过链接下载文件</h4>
        <a href="/day06/download/cors.zip">压缩包</a>
        <a
            href="https://img-blog.csdnimg.cn/534762daa9654b61a89b341a7a82e123.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5LqU6Iqx5ryP,size_20,color_FFFFFF,t_70,g_se,x_16#pic_center">图片</a>
    </div> -->
    <script>
        var imgUrl = 'https://img-blog.csdnimg.cn/534762daa9654b61a89b341a7a82e123.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5LqU6Iqx5ryP,size_20,color_FFFFFF,t_70,g_se,x_16#pic_center'
        
        function downloadIamge(downUrl, name = new Date().valueOf()) {//下载地址和名字(时间戳)
            console.log('下载:', downUrl)
            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 = downUrl;
        }


        function downloadUrlFile(url, fileName = new Date().valueOf()) {
            const url2 = url.replace(/\\/g, '/');
            const xhr = new XMLHttpRequest();
            xhr.open('GET', url2, true);
            xhr.responseType = 'blob';
            //xhr.setRequestHeader('Authorization', 'Basic a2VybWl0Omtlcm1pdA==');
            // 为了避免大文件影响用户体验,建议加loading
            xhr.onload = () => {
                if (xhr.status === 200) {
                    var blob = xhr.response
                    const urlObject = window.URL || window.webkitURL || window;
                    const export_blob = new Blob([blob]);
                    //createElementNS() 方法可创建带有指定命名空间的元素节点。此方法可返回一个 Element 对象。
                    const save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
                    save_link.href = urlObject.createObjectURL(export_blob);
                    let type = blob.type.split('/')[1] || ''
                    save_link.download = fileName + '.' + type;
                    save_link.click();
                }
            };
            xhr.send();
        }




        // function downloadImg(imgUrl) {
        //     var url = imgUrl                            // 获取图片地址
        //     var a = document.createElement('a')          // 创建一个a节点插入的document
        //     var event = new MouseEvent('click')           // 模拟鼠标click点击事件
        //     a.download = '图片名字'                  // 设置a节点的download属性值
        //     a.href = url;
        //     a.dispatchEvent(event)                        // 触发鼠标点击事件
        //     // imgUrl = "https://cdn.bootcdn.net/ajax/libs/jsencrypt/3.2.1/jsencrypt.js

        //     // const eleLink = document.createElement('a')
        //     // eleLink.download = 'tupian.png'
        //     // eleLink.style.display = 'none'
        //     // eleLink.href = imgUrl
        //     // // 触发点击
        //     // document.body.appendChild(eleLink)
        //     // eleLink.click()
        //     // // 然后移除
        //     // document.body.removeChild(eleLink)
        // }
    </script>
</body>

</html>

在这里插入图片描述

相关阅读

JavaScript实现图片上传到页面

;