Jay*_*ong 6 javascript web typescript webapi vite
现在所有主要浏览器都支持DecompressionStream API,但我不知道如何使用它fetch()在浏览器中解压缩 gzip 文件。
以下代码适用于 base64 字符串:
\nconst decompress = async (url) => {\n const ds = new DecompressionStream(\'gzip\');\n const response = await fetch(url);\n const blob_in = await response.blob();\n const stream_in = blob_in.stream().pipeThrough(ds);\n const blob_out = await new Response(stream_in).blob();\n return await blob_out.text();\n};\n\ndecompress(\n \'data:application/octet-stream;base64,H4sIAAAAAAAAE/NIzcnJVyjPL8pJAQBSntaLCwAAAA==\'\n).then((result) => {\n console.log(result);\n});Run Code Online (Sandbox Code Playgroud)\r\n但是,如果我在 MacOS 上hello.txt.gz使用创建文件(是内容为“hello world”的纯文本文件),则上面的函数会抛出错误。gzip hello.txthello.txt
decompress(\'/hello.txt.gz\').then((result) => {\n console.log(result);\n});\nRun Code Online (Sandbox Code Playgroud)\ndecompress(\'/hello.txt.gz\').then((result) => {\n console.log(result);\n});\nRun Code Online (Sandbox Code Playgroud)\n编辑
\nStackblitz有一个可复制的演示。
\n感谢@kaiido\的帮助(见问题评论),我们发现这个错误是由Vite服务器引起的。开发服务器提供.gz带有错误标头的文件。
"content-encoding": "gzip"\n\xe2\x80\x8b\xe2\x80\x8b"content-length": "42"\n"content-type": "text/plain"\nRun Code Online (Sandbox Code Playgroud)\n解决方法是重命名文件以使用不同的扩展名(例如hello.txt.gz\xe2\x86\x92 hello.txt.gzip)。
| 归档时间: |
|
| 查看次数: |
1845 次 |
| 最近记录: |