Blob实现二进制图片下载


<!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>Document</title>
    <script src="./js/jquery-1.10.2.js"></script>
</head>

<body>
    <a href="https://bpic.588ku.com/element_origin_min_pic/21/03/21/c7ef9d4385008b5bf860567675e0abf5.jpg"
        download>直接下载</a>
    <img src="https://qiniu.guet.link/img/c7477a56b9f0b5f294a77013734f1d0c.jpeg" alt="" srcset="">
    <script>
        // 背景:
        // 我看了一下报文,后端同样要配置响应头access-control-allow-origin: *
        // 也就是说a标签的download属性不管你后端允许不允许跨域请求,只要你跨域了就会跳转到图片站点
        // 而xhr需要后端允许跨域访问,拿到二进制数组,在前端映射url,通过download属性声明 完成下载

        function Download(url) {
            const XHR = new XMLHttpRequest();
            XHR.responseType = 'blob';
            //参数说明 https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/responseType
            XHR.open('GET', url);
            XHR.onload = () => {
                const fileBlob = XHR.response;
                console.log(fileBlob);

                //创建url映射内存中的二进制图片
                const fileUrl = URL.createObjectURL(fileBlob);

                console.log(fileUrl);
                let element = document.createElement('a');
                element.setAttribute('href', fileUrl);
                element.setAttribute('download', '');
                element.innerHTML = '下载';
                $('body').append(element);

                let elementImg = document.createElement('img');
                elementImg.setAttribute('src', fileUrl);
                $('body').append(elementImg);

            }
            XHR.send();
        }

        //Download('https://bpic.588ku.com/element_origin_min_pic/21/03/21/c7ef9d4385008b5bf860567675e0abf5.jpg');
        Download('http://127.0.0.1:5500/sample.pdf');


    </script>
</body>

</html>

文章作者: iamfugui
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 iamfugui !
评论