vue实现文件解压缩

1. 使用CompressionStream API实现压缩

这里开启了多线程解压缩

<template>
  <div class="page">
    <input type="file" placeholder="选择文件" id="file" />
    <button @click="compress('compress')">压缩</button>
    <button @click="compress('decompress')">解压</button>
  </div>
</template>
<script setup lang="ts">
import { onMounted } from "vue";
let file: File | null = null; //源文件
let file_zip: Blob | null = null; //压缩后的文件
onMounted(() => {
  document.getElementById("file")?.addEventListener("change", (e: any) => {
    file = e.target.files[0];
    console.log("原始文件", file);
  });
});
let compress = async (type: string) => {
  const worker = new Worker(new URL("/src/utils/fileWorker.ts", import.meta.url));
  worker.postMessage({ file: type == "compress" ? file : file_zip, type });
  worker.onmessage = (e) => {
    let {
      data: { file, type },
    } = e;
    if (type == "compress") {
      file_zip = file;
      console.log("压缩", file);
    } else {
      console.log("解压", file);
    }
    worker.terminate();
  };
};
</script>
<style lang="less" scoped></style>

2.线程:

onmessage = async (file: any) => {
  // 向主线程发送消息
  let { file: data, type } = file.data;
  let compressStream;
  let blob;
  if (type == "compress") {
    compressStream = new CompressionStream("gzip");
  } else {
    compressStream = new DecompressionStream("gzip");
  }
  const readStream = await data?.stream();
  const compressdReadStream = readStream?.pipeThrough(compressStream);
  blob = await new Response(compressdReadStream, {
    headers:
      type == "compress"
        ? { "Content-Type": "application/gzip" }
        : { "Content-Type": "text/plain;charset=utf-8" },
  }).blob();

  postMessage({ file: blob, type });
};

3.查看压缩效果

4.好吧,压缩效果不明显,这个API没什么用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值