js压缩文件读取处理
1.引入必须依赖库jszip+jsutils=>>>建议使用以下版本,其他版本的jszip会报错
<!--zip文件读取-->
<script src="https://cdn.bootcss.com/jszip/2.1.0/jszip.min.js"></script>
<script src="https://cdn.bootcss.com/jszip-utils/0.0.2/jszip-utils.min.js"></script>
2.实例化jsZip对象并读取文件:
<script>
JSZipUtils.getBinaryContent('http://static.yygo.tv/Gift/o_1c3239h691nd2uohmf414b8dlia.zip', function (err, data) {
if (err) {
throw err; // or handle err
}
var zip = new JSZip(data);
var imgArr = [],
image = {};
for (var i in zip.files) {
imgArr.push(i)
};
var len = imgArr.length;
for (var j = 1; j < len; j++) {//循环图片Base64
var fileName = imgArr[j],
buffer = zip.file(imgArr[j]).asArrayBuffer(),
str = _arrayBufferToBase64(buffer),
pIndex = fileName.indexOf('.'),
type = fileName.substr(pIndex + 1),
re = 'data:image/' + type + ';base64,';
document.getElementById("gift").src = re + str;
image[fileName] = re + str;
};
console.log(image)
})
//img to Base64
function _arrayBufferToBase64(buffer) {
var binary = '';
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
}
</script>
Tip=>jsZip读取的data为对象,以上操作将其转为ARRAY形式,并使用BASE64转码函数将读取到的img文件的ARRAYBUFFER数据转为BASE64,buffer参数为每个图片的文件名,可通过zip.file('')||zip.folder()读取文件名或文件夹