我有点困惑Accept-Encoding
。我有 Web 服务,它可以接受使用 POST 方法提交的压缩文件。我在下面添加了代码,用于查找Accept-Encoding: gzip
和解压缩提交的文件。问题在于从 Internet 浏览器提交的文件。请求标头包含 gzip,但文件实际上并未压缩。也许有人可以帮助了解如何检测文件是否实际压缩?
var httpPostedFile = httpRequest.Files[0];
var contentLength = httpPostedFile.ContentLength;
var buffer = new byte[contentLength];
httpPostedFile.InputStream.Read(buffer, 0, contentLength);
const string acceptEncoding = "Accept-Encoding";
if (httpRequest.Headers[acceptEncoding] != null && httpRequest.Headers[acceptEncoding].Contains("gzip"))
{
buffer = Decompress(buffer);
}
static byte[] Decompress(byte[] gzip)
{
using (var stream = new GZipStream(new MemoryStream(gzip), CompressionMode.Decompress))
{
const int size = 4096;
var buffer = new byte[size];
using (var memory = new MemoryStream())
{
int count;
do
{
count = stream.Read(buffer, 0, size);
if (count > 0)
{
memory.Write(buffer, 0, count);
}
}
while (count > 0);
return memory.ToArray();
}
}
}