Javascript GZIP和btoa并使用C#解压缩 [英] Javascript GZIP and btoa and decompress with C#
问题描述
我正在开发一个应用程序,其中我使用pako.gzip压缩大型JSON数据,然后使用btoa函数将其设置为base64string以便将数据发布到服务器.在我写的JavaScript中:
i am developing an application where i compress large JSON data using pako.gzip and then use the btoa function to make it base64string in order to post the data to the server. In the javascript i wrote:
var data = JSON.stringify(JSONData);
var ZippedData = pako.gzip(data, { to: 'string' });
var base64String = btoa(ZippedData);
/* post to server*/
$http.post("URL?base64StringParam=" + base64String").then(function (response) {
//do stuff
});
问题是我需要在发布后再次用C#代码解压缩数据,以便对其进行其他处理.在C#代码中,我写道:
the problem is that i need to decompress the data again in C# code after posting in order to do other workings on it. In the C# code i wrote:
byte[] data = Convert.FromBase64String(base64StringParam);
string decodedString = System.Text.ASCIIEncoding.ASCII.GetString(data);
Encoding enc = Encoding.Unicode;
MemoryStream stream = new MemoryStream(enc.GetBytes(decodedString));
GZipStream decompress = new GZipStream(stream, CompressionMode.Decompress);
string plainDef = "";
我在这里得到错误
using (var sr = new StreamReader(decompress))
{
plainDef = sr.ReadToEnd();
}
解码时发现无效数据.
在C#中解压缩数据的任何帮助将不胜感激
any help to decompress the data back in C# will be appreciated
编辑:总结需要做的事情javascript执行以下操作:
EDIT:to sum up what needed to be done javascript does the following:
纯文本>>到>> gzip字节>>到>> base64字符串
Plain text >> to >> gzip bytes >> to >> base64 string
我需要C#来做相反的事情:
i need C# to do the reverse:
Base64 >>到>>解压缩字节>>到>>纯文本
Base64 >> to >> unzip bytes >> to >> plain text
推荐答案
在客户端使用:
let output = pako.gzip(JSON.stringify(obj));
发送为:内容类型":应用程序/八位字节流"
send as: 'Content-Type': 'application/octet-stream'
====================
=====================
然后用C#:
[HttpPost]
[Route("ReceiveCtImage")]
public int ReceiveCtImage([FromBody] byte[] data)
{
var json = Decompress(data);
return 1;
}
public static string Decompress(byte[] data)
{
// Read the last 4 bytes to get the length
byte[] lengthBuffer = new byte[4];
Array.Copy(data, data.Length - 4, lengthBuffer, 0, 4);
int uncompressedSize = BitConverter.ToInt32(lengthBuffer, 0);
var buffer = new byte[uncompressedSize];
using (var ms = new MemoryStream(data))
{
using (var gzip = new GZipStream(ms, CompressionMode.Decompress))
{
gzip.Read(buffer, 0, uncompressedSize);
}
}
string json = Encoding.UTF8.GetString(buffer);
return json;
}
这篇关于Javascript GZIP和btoa并使用C#解压缩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!