客户端从 C# 压缩字符串解压回字符串

Client side decompression back to string from C# compression of string

我有一些大数据集,我想在发送给我的客户之前对其进行压缩。压缩有效。

利用这段代码将我的数据变成一个漂亮的小型 base64String:

示例:字符串 mytest = "This is some test text.";

        public static string Compress(string mytest)
    {
        byte[] buffer = System.Text.Encoding.UTF8.GetBytes(text);
        MemoryStream ms = new MemoryStream();
        using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))
        {
            zip.Write(buffer, 0, buffer.Length);
        }

        ms.Position = 0;
        MemoryStream outStream = new MemoryStream();

        byte[] compressed = new byte[ms.Length];
        ms.Read(compressed, 0, compressed.Length);

        byte[] gzBuffer = new byte[compressed.Length + 4];
        System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
        System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
        return Convert.ToBase64String(gzBuffer);
    }

在客户端,我需要倒着走。

我可以使用 (library):

将 base64 字符串转换回字节数组
var byteArray = Base64Binary.decodeArrayBuffer(source);

然后使用 pako.js 我可以放气 gzip 压缩内容:

var deflate = new pako.Deflate({ level: 1 });
deflate.push(uintArray, true);
if (deflate.err) { throw new Error(deflate.err); }

最后,我应该能够将其转换回我的文本:

var encodedString = String.fromCharCode.apply(null, deflate.result)
var decodedString = decodeURIComponent(encodedString);

问题是虽然我没有得到任何错误,但我没有得到预期的结果,这应该是原始字符串 - "This is some test text."

输出是这样的(不能全部粘贴): xg``ïæ

有没有想过我错过了什么?

您需要在前端使用 pako.Inflate
此外,您需要在解码之前删除添加到前端 gzBuffer 前面的 4 个字节大小。

像这样的东西应该可以工作:

// "cookies rule the world" compressed with your c# code
let sample = "FgAAAB+LCAAAAAAABABLzs/PzkwtVigqzUlVKMlIVSjPL8pJAQBkkN7rFgAAAA==";

// decode base64 & convert to Uint8 Array
let binary = atob(sample);
let bytes = Uint8Array.from(binary, c => c.charCodeAt(0));

// You appended the length at the start of gzBuffer, so you need to remove those bytes
bytes = bytes.slice(4);

// inflate the message & convert it to a string
let inflated = pako.inflate(bytes);
let message =  String.fromCharCode.apply(null, inflated);
console.log(message);
<script src="https://raw.githubusercontent.com/danguer/blog-examples/master/js/base64-binary.js"></script>
<script src="https://unpkg.com/pako@1.0.10/dist/pako.min.js"></script>