我已经用.gz压缩在blob存储上存储了一个json文件,所以我的文件url看起来像这个https://abcd.blob.core.windows.net/mydir/largefilecompressed.json.gz。因此,现在我需要理解如何在ReactJs中获取它并解压缩到largefilecompressed.json。
该文件是2-3 MB,没有压缩,在低网络区域,它需要时间负载和影响用户体验,这就是为什么我想避免从服务器这样做。
发布于 2021-07-13 19:03:31
您没有理由不能解压缩存储在react或javascript中的blob。您可以解压缩它,使用网络组装,您可以做到它几乎是本地性能。
您可以使用帕科库来完成这项工作。
从文件上看,
充气 使用充气/ungzip和选项来解压缩数据。默认情况下,通过包装头自动检测格式。
下面是示例代码,其中有些json.gz是从github随机抽取的。
const urls = [
'https://raw.githubusercontent.com/NazarHarashchak/MobileBanking/9155a04a3ff064167537a7c32f9cca356a5c3ab4/FrontEnd/node_modules/.cache/eslint-loader/b3fa51dc9159babf532b97696dacb328bf0a70dc.json.gz',
'https://raw.githubusercontent.com/mongodb-university/mflix-python/d9667e709bd400f3d3dbd6e7f1474b3702d9d5fa/data/mflix/comments.metadata.json.gz',
'https://raw.githubusercontent.com/dump-sauraj/realme_rmx2185_dump964/3a9c42cac2977a13e43ca8bf1ff886fca730f158/system/system/etc/protolog.conf.json.gz'
]
async function exec(i = 0) {
console.group('file: ', i);
try {
// fetch file with CORS enabled
const res = await fetch(urls[i], {
mode: 'cors'
});
// convert to arrayBuffer for further processing
const buf = await res.arrayBuffer();
// or get blob using `await res.blob()`
// and convert blob to arrayBuffer using `await blob.arrayBuffer()`
console.log('input size: ', buf.byteLength);
// decompress file
const outBuf = pako.inflate(buf);
console.log('output size: ', outBuf.byteLength);
// convert arrayBuffer to string
const str = new TextDecoder().decode(outBuf);
// console.log('json string', str);
// print json object
console.log('json object', JSON.parse(str));
} catch (err) {
console.error('unable to decompress', err);
}
console.groupEnd('file: ', i);
}
async function init() {
for (let i in urls) await exec(i)
}
init()<script src="https://cdnjs.cloudflare.com/ajax/libs/pako/2.0.3/pako.min.js" integrity="sha512-yJSo0YTQvvGOqL2au5eH0W4K/0FI0sTJuyHjiHkh0O31Lzlb814P0fDXtuEtzOj13lOBZ9j99BjqFx4ASz9pGA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
我尝试了几个软件包,如wasm-平板、wasm-gzip、d5ly和帕科,但只有pako的成功率最高。如果你这样想的话,你可以考虑他们。
编辑:添加完整json字符串的代码注释和禁用的console.log
https://stackoverflow.com/questions/68254992
复制相似问题