一篇文章介绍JSZip预览压缩包中的文件

安装依赖

npm i jszip

前提准备

准备好一个压缩包,格式为zip,存放两张png图片。

代码实现

<template>
  <h1>JSZip,预览压缩包中的文件</h1>
  <img v-for="(n,m) in picArr.arr"
       :src="n"
       :style="{width:'200px'}"
       :key="m">
  <div>需要压缩的包(zip)</div>
  <input type="file"
         @change="fn">
</template>
​
<script setup>
import { reactive } from '@vue/reactivity'
import JSZip from 'jszip'
​
let picArr = reactive({ arr: [] })
const fn = (e) => {
  // console.log(e.target.files[0]);
  let zip = new JSZip()
  // loadAsync() 读取现有的zip,并在当前文件夹级别合并当前JSZip对象中的数据
  // 如果两个具有相同的名称,则加载的一个将替换另一个
  zip.loadAsync(e.target.files[0])
    .then(zipdata => {
      // console.log(zipdata.files);
      for (let n in zipdata.files) {
        // console.log(zipdata.files[n]);
​
        // .file(name) 读取文件在当前目录
        zipdata
          // 获得指定文件里面的文件名字
          .file(zip.files[n].name)
          // 指定返回结果类型
          .async('base64')
          .then(res => {
            // 打印base64
            // console.log(res);
            let imgBase64 = 'data:image/jpeg;base64,' + res
            picArr.arr.push(imgBase64)
          })
      }
    })
}
</script>
​
<style scoped>
div {
  margin: 0 auto;
}
</style>

结果显示

代开浏览器页面点击按钮上传压缩包。

结果会在浏览器页面中显示压缩包里的图片内容。

举一反三,如果压缩包里面的内容是文本信息呢,应该怎么显示?

关键部分:async('text') 实现对文本内容的解析。

准备一个文本压缩包如下。

代码修改如下

<template>
  <h1>JSZip,预览压缩包中的文件</h1>
  <img v-for="(n,m) in picArr.arr"
       :src="n"
       :style="{width:'200px'}"
       :key="m">
  <div>需要压缩的包(zip)</div>
  <input type="file"
         @change="fn">
  <h2>{{ zipContent }}</h2>
</template>
​
<script setup>
import { reactive, ref } from '@vue/reactivity'
import JSZip from 'jszip'
​
let picArr = reactive({ arr: [] })
let zipContent = ref('')
​
const fn = (e) => {
  // console.log(e.target.files[0]);
  let zip = new JSZip()
  // loadAsync() 读取现有的zip,并在当前文件夹级别合并当前JSZip对象中的数据
  // 如果两个具有相同的名称,则加载的一个将替换另一个
  zip.loadAsync(e.target.files[0])
    .then(zipdata => {
      // console.log(zipdata.files);
      for (let n in zipdata.files) {
        // console.log(zipdata.files[n]);
​
        // .file(name) 读取文件在当前目录
        zipdata
          // 获得指定文件里面的文件名字
          .file(zip.files[n].name)
          // 指定返回结果类型
          .async('text')
          .then(res => {
            // 打印文本信息
            console.log(res);
            zipContent.value = res
          })
      }
    })
}
</script>
​
<style scoped>
div {
  margin: 0 auto;
}
</style>

结果显示

总结

通过上面的案例代码,可以举一反三进行预览显示视频和音频等其他类型文件,可以仔细了解JSZip官网中的api。

相关jszip的api 方法 可以查询https://stuk.github.io/jszip

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr.怪兽

希望大家能够多多支持,我会继续

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值