繁体   English   中英

使用 HTML5 和 Javascript 进行客户端压缩

[英]Client side compression with HTML5 and Javascript

我正在开发 web 应用程序,我们允许用户将文件上传到我们的服务器。 我试图在将文件上传到服务器之前进行客户端压缩。 使用 HTML5 和 JavaScript 实现此目的的更好方法是什么。

谢谢。

做你想做的事情的常用机制是使用FileReader和 JavaScript 客户端压缩库(即compressjs )。

在 2022 年,如果浏览器支持CompressionStreamFormDataResponse ,那就太简单了。

在下面的示例中,我使用FormData从表单中收集所有字段。 然后我使用文件中的可读 stream 和 pipe 通过压缩 stream。然后我使用Response从压缩的 stream 中读取所有内容并将其返回到 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM