前端js处理接口返回的压缩包(亲测可用)

zhaolisha 2020-06-16

依赖jszip.js和FileSaver.js两个js库,可以到官网下载

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

<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <script src="./jquery3.5.1.js"></script>
    <script src="./jszip.min.js"></script>
    <script src="./FileSaver.min.js"></script>
    <script type="text/javascript">
        $(function () {
            var xmlhttp;
            xmlhttp = new XMLHttpRequest();
            xmlhttp.open("GET", "http://192.168.xx.xx:xx/tasks/screenshots/120", true);  // 此接口返回一个压缩包,其中包含若干jpg格式的图片,本demo将图片展示到前台
            // xmlhttp.setRequestHeader("Authorization", "Bearer xxxx");  // 这是认证报头,按需
            xmlhttp.responseType = "blob";
			
            xmlhttp.onload = function () {
                if (this.status == 200) {
                    var blob = this.response;
                    var new_zip = new JSZip();
                    new_zip.loadAsync(blob).then(function (file) {
			var files = file.files;
			for (it in files) {
			var zipobj = files[it];
				if (!zipobj.dir) {
				      new_zip.file(it).async("blob").then(function (blob) {
				            var imgUrl = URL.createObjectURL(blob);
				            $("#kkk" ).attr("src", imgUrl);
				      });
				 }
			      }
			});
                }
            }
            xmlhttp.send();
        });
    </script>
</head>

<body>
	<img id="kkk" src=""/>
</body>

</html>

相关推荐