[英]GZip decompression in JavaScript with offset
我嘗試使用的 API 正在返回 base64 編碼的響應。 響應首先使用具有 4 位偏移量的 GZip 進行壓縮,然后進行 base64 編碼。 我嘗試使用 JavaScript( pako和zlib )解析響應,但在這兩種情況下,它都失敗了。 API 有一個 C# 代碼示例,說明響應解壓縮應該如何工作,但我真的不知道如何將其轉換為 JavaScript。 那么誰能幫我把這個函數轉換成 JavaScript 或者只是給我一些關於如何處理 4 字節偏移量的提示? 我在圖書館的文檔中沒有找到任何相關的內容。
public string Decompress(string value)
{
byte[] gzBuffer = Convert.FromBase64String(value);
using (MemoryStream ms = new MemoryStream())
{
int msgLength = BitConverter.ToInt32(gzBuffer, 0);
ms.Write(gzBuffer, 4, gzBuffer.Length - 4);
byte[] buffer = new byte[msgLength];
ms.Position = 0;
using (System.IO.Compression.GZipStream zip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress))
{
zip.Read(buffer, 0, buffer.Length);
}
return System.Text.Encoding.Unicode.GetString(buffer, 0, buffer.Length);
}
}
我將使用fflate (免責聲明,我是作者)來做到這一點。 如果您想為該行翻譯該函數行:
// This is ES6 code; if you want better browser compatibility
// use the ES5 variant.
import { gunzipSync, strToU8, strFromU8 } from 'fflate';
const decompress = str => {
// atob converts Base64 to Latin-1
// strToU8(str, true) converts Latin-1 to binary
const bytes = strToU8(atob(str), true);
// subarray creates a new view on the same memory buffer
// gunzipSync synchronously decompresses
// strFromU8 converts decompressed binary to UTF-8
return strFromU8(gunzipSync(bytes.subarray(4)));
}
如果你不知道 ES6 是什么:
在您的 HTML 文件中:
<script src="https://cdn.jsdelivr.net/npm/fflate/umd/index.js"></script>
在你的 JS 中:
var decompress = function(str) {
var bytes = fflate.strToU8(atob(str), true);
return fflate.strFromU8(fflate.gunzipSync(bytes.subarray(4)));
}
我想提一下,如果你要在最后累積成一個字符串,流幾乎完全沒用,所以 C# 代碼是次優的。 同時,由於您使用的是標准庫,因此它是唯一的選擇。
此外,如果可能的話,我強烈建議使用回調變體(即gunzip
而不是gunzipSync
),因為它在單獨的線程上運行以避免導致瀏覽器凍結。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.