前端(JS\VUE)JSZIP读取压缩包文件内容,JSZIP解决乱码

前端(JS\VUE)JSZIP读取压缩包文件内容,JSZIP解决乱码

主要需要需要安装jszip

npm i jszip -S

下面是用vue 做为演示(如果只用vue其实可以省略jquery)

<template>

<div>

<h3>选择一个压缩文件</h3>

<inputtype="file"id="file"name="file"multiple/><br/>

<divid="result_block"class="hidden">

<h3>压缩包中文件列表 :</h3>

<divid="result"></div>

</div>

</div>

</template>

<script>

importJSZipfrom"jszip";

import$from"jquery";

exportdefault{

methods: {

handleFile(f) {

let_this=this;

//显示Zip名和创建filesname的ul容器

var$title=$("<h4>", {

text:f.name,

     });

var$fileContent=$("<ul>");

$("#result").append($title);

$("#result").append($fileContent);

// 1) read the Blob

JSZip.loadAsync(f).then(

function(zip) {

// var dateAfter = new Date();

// $title.append($("<span>", {

//     "class": "small",

//     text:" (loaded in " + (dateAfter - dateBefore) + "ms)"

Object.keys(zip.files).forEach((item)=>{

if(item.slice(item.lastIndexOf("."))==".json") {

zip.files[item].async("blob").then(function(blob) {

_this.readTextAs(blob,"utf-8",function(error,text) {

$("#result").html(`<p>文件:${item}的内容</p>`+text);

console.log(JSON.parse(text));

               });

             });

           }

         });

// zip.files['sssss.txt'].async("string").then(function(con){

//     console.log(con);

// })

       },

function(e) {

$("#result").append(

$("<div>", {

class:"alert alert-danger",

text:"Error reading "+f.name+": "+e.message,

           })

         );

       }

     );

   },

readTextAs(arrayBuffer,encoding,callback) {

varreader=newFileReader();

// EDIT : see my other comment below

// var blob = JSZip.utils.arrayBuffer2Blob(arrayBuffer);

varblob=newBlob([arrayBuffer]);

reader.onload=function(evt) {

callback(null,evt.target.result);

     };

reader.onerror=function(evt) {

callback(evt.error,null);

     };

reader.readAsText(blob,encoding);

   },

  },

mounted() {

let_this=this;

$("#file").on("change",function(evt) {

$("#result").html("");

$("#result_block").removeClass("hidden").addClass("show");

varfiles=evt.target.files;

for(vari=0;i<files.length;i++) {

_this.handleFile(files[i]);

     }

   });

  },

};

</script>

<style>

code{

display:block;

padding:10px;

background:#eee;

}

</style>

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容