Compression Stream API

Compression Stream API

使用 gzip 或者默认格式压缩和解压缩数据


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Compression Stream API</title>
  </head>
  <body>
    <strong>Compression Stream API</strong>
    <hr />
    <input type="file" class="file" />
    <button type="button" class="btn-compress">压缩文件</button>
    <button type="button" class="btn-decompress">文件解压</button>

    <script>
      // Compression Stream API
      // 使用 gzip 或者默认格式压缩和解压缩数据

      const btnCompress = document.querySelector('.btn-compress');
      const btnDecompress = document.querySelector('.btn-decompress');

      btnDecompress.addEventListener('click', () => {
        const uploadFile = document.querySelector('.file').files[0];

        if (!uploadFile) return;

        decompessFile(uploadFile);
      });

      /**
       * 解压文件
       * @param {File} file 文件对象
       */
      async function decompessFile(file) {
        // 创建 gzip 解压流
        const decompressStream = new DecompressionStream('gzip');
        // 创建文件读取流
        const readStream = await file.stream();

        // 解压文件并写入解压流
        const decompressdReadStream = readStream.pipeThrough(decompressStream);
        // console.log("decompressdReadStream => ", decompressdReadStream)

        const blob = await new Response(decompressdReadStream, {
          headers: { 'Content-Type': 'text/plain;charset=utf-8' },
        }).blob();
        console.log('blob => ', blob);

        open(URL.createObjectURL(blob));
        // downloadFile(blob, file.name);
      }

      btnCompress.addEventListener('click', () => {
        const uploadFile = document.querySelector('.file').files[0];

        if (!uploadFile) return;

        compessFile(uploadFile);
      });

      /**
       * 压缩文件
       * @param {File} file 文件对象
       */
      async function compessFile(file) {
        // 创建 gzip 压缩流
        const compressStream = new CompressionStream('gzip');
        // 创建文件读取流
        const readStream = await file.stream();

        // 压缩文件并写入压缩流
        const compressdReadStream = readStream.pipeThrough(compressStream);
        // console.log("compressdReadStream => ", compressdReadStream)

        const blob = await new Response(compressdReadStream, {
          headers: { 'Content-Type': 'application/gzip' },
        }).blob();
        console.log('blob => ', blob);

        downloadFile(blob, file.name);
      }

      /**
       * 下载文件
       * @param {Blob} blob 二进制数据
       * @param {string} filename 文件名
       */
      function downloadFile(blob, filename = parseInt(Date.now() / 1000)) {
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `${filename}.gz`;
        link.click();
      }
    </script>
  </body>
</html>
posted @ 2024-04-28 21:55  _clai  阅读(38)  评论(0编辑  收藏  举报