使用JSZip.js、FileSaver.js前端打包下载图片

原创
2019/05/28 10:55
阅读数 5.3K

前端打包下载图片

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<img src="assets/logo.png"  
     class="yaojianbaogao" width="50"   data-title="霍痕"
     data-alt="1.png">
<img src="assets/logo.png"  
     class="yaojianbaogao" width="50"   data-title="霍痕"
     data-alt="2.png">

<a href="javascript:;" onclick="downloadzip()">打包下载</a>

<script src="https://cdn.bootcss.com/jszip/3.2.0/jszip.min.js"></script>
<script src="https://cdn.bootcss.com/FileSaver.js/2014-11-29/FileSaver.min.js"></script>
<script>
    function downloadzip() {
        var imgs = document.getElementsByClassName('yaojianbaogao');
        var zip = new JSZip();
        var file_name = 'images.zip';
        Array.from(imgs).forEach((item,index,array) => {
            file_name = '';
            var zipFolder = zip.folder('images');
            var img = new Image();
            img.setAttribute("crossOrigin",'Anonymous')
            img.src = item.getAttribute('src');
            img.onload = function(){//图片加载完,再draw 和 toDataURL
                var canvas = document.createElement("canvas");
                canvas.width = img.width;
                canvas.height = img.height;
                var ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0, img.width, img.height);
                var imgdata = canvas.toDataURL();
                var img_arr = imgdata.split(',');
                zipFolder.file(item.getAttribute('data-alt'), img_arr[1], {base64: true});
                if(Object.getOwnPropertyNames((zipFolder.files)).length -1 === array.length) {
                    zip.generateAsync({type: "blob"}).then(function (content) {
                        saveAs(content, file_name);
                    });
                }
            };
        });
    }
</script>
</body>
</html>

toDataUrl()方法可能会跨域,如果用nginx可以直接加一个header

add_header 'Access-Control-Allow-Origin' '*';

展开阅读全文
加载中

作者的其它热门文章

打赏
0
0 收藏
分享
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部