之前是直接传没有经过压缩的文件字节,有时文件过大的话,可能占宽带就多,宽带流量都是钱。后来有个想法,在客户端把文件进行压缩,把压缩的文件流发给服务端进行解压。
1,先修改项目中Startup.cs文件中ConfigureServices()方法中的代码:
//注册压缩响应
services.AddResponseCompression((options) =>
{
options.EnableForHttps = true;
options.Providers.Add<Microsoft.AspNetCore.ResponseCompression.GzipCompressionProvider>();
});
2 ,先修改项目中Startup.cs文件中Configure(IApplicationBuilder app, IWebHostEnvironment env)方法中的代码:
//使用gzip压缩
app.UseResponseCompression();
3,在控制层处理传过来压缩文件进行处理。
var formFiles = (Microsoft.AspNetCore.Http.FormFileCollection)formCollection.Files;
byte[] bytes = new byte[] { };
foreach (var item in formFiles)
{
bytes = DeZip(item.OpenReadStream());
}
string html2 = System.Text.Encoding.UTF8.GetString(bytes);
public static byte[] DeZip(Stream stream)
{
byte[] buffer2 = new byte[1024];
int length;
using (var gz = new GZipStream(stream, CompressionMode.Decompress))
{
using (MemoryStream msTemp = new MemoryStream())
{
while ((length = gz.Read(buffer2, 0, buffer2.Length)) != 0)
{
msTemp.Write(buffer2, 0, length);
}
return msTemp.ToArray();
}
}
}