客户端压缩与HTML5和Javascript

Client side compression with HTML5 and Javascript

本文关键字:Javascript HTML5 压缩 客户端      更新时间:2023-09-26

我在一个web应用程序上工作,我们允许用户上传文件到我们的服务器。我试图在上传文件到服务器之前做客户端压缩。使用HTML5和JavaScript实现这一目标的更好方法是什么呢?

谢谢。

你想要的通用机制是使用FileReader和JavaScript客户端压缩库(即compressjs)。

在2022年,如果浏览器支持CompressionStream, FormData和Response,这几乎太简单了。

在下面的示例中,我使用FormData从表单中收集所有字段。然后我使用文件中的可读流,并通过压缩流将其管道化。然后我使用Response从压缩流中读取所有内容,并以blob形式返回。

async function compress(file, encoding = 'gzip') {
  try {
    return {
      data: await new Response(file.stream().pipeThrough(new CompressionStream(encoding)), {
        headers: {
          'Content-Type': file.type
        },
      }).blob(),
      encoding,
    };
  } catch (error) {
    // If error, return the file uncompressed
    console.error(error.message);
    return {
      data: file,
      encoding: null
    };
  }
}
theForm.addEventListener(
  'submit',
  (event) => event.preventDefault()
)
theForm.addEventListener(
  'input',
  async function(event) {
    // collect all fields
    const fd = new FormData(theForm);
    // Get 'file handle' from imput elemen
    const file = fd.get('theFile');
    if (!file) return
    const encoding = fd.get('theEncoding');
    const compressed = await compress(file, encoding);
    theMessage.value = [
      'Compressed with', compressed.encoding,
      'Source file was', file.size, 'bytes',
      'and the compressed file', compressed.data.size,
      'saving', ((1 - compressed.data.size / file.size) * 100)
      .toFixed(0),
      '%.'
    ].join(' ')
  }
)
form>* {
  display: block;
  width: 100%;
}
<form id="theForm">
  <select name="theEncoding">
    <option>gzip</option>
    <option>deflate</option>
    <option>deflate-raw</option>
  </select>
  <input type="file" name="theFile" id="theFile">
</form>
<output id="theMessage"></output>

相关文章: