Diza1986 2020年11月25日
求教!HttpClient上传文件并对Request进行压缩
客户端 C#(Winform .netFramework 4.8)
(测试用)服务器端 nodejs (express+multer+zlib)

在不进行压缩的前提下,可以正常的上传文件
客户端C#代码概要

string filePath = "SOME FILE PATH";

using (var httpClient = new HttpClient())
{
using (var form = new MultipartFormDataContent())
{
using (var streamContent = new StreamContent(File.OpenRead(filePath)))
{
form.Add(streamContent, "file", Path.GetFileName(filePath));
HttpResponseMessage response = httpClient.PostAsync(url, form).Result;
}
}
}


服务器端nodejs代码概要

var storage = multer.memoryStorage()
var upload = multer({
storage: storage
})

app.post('/compress', upload.single('file'), async (req, res) => {
try {
console.log(` file: ${JSON.stringify(req.file)}`);
...
}
...
}


然后尝试Gzip压缩
客户端C#代码概要
--先做成了一个压缩用的扩张类

public class GzipCompressedContent : HttpContent
{
private readonly HttpContent _content;

public GzipCompressedContent(HttpContent content)
{
// Copy original headers
foreach (KeyValuePair<string, IEnumerable<string>> header in content.Headers)
{
Headers.TryAddWithoutValidation(header.Key, header.Value);
}

Headers.ContentEncoding.Add("gzip");
_content = content;
}

protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
using (var gzip = new GZipStream(stream, CompressionMode.Compress, true))
{
// Compress the entire original content
await _content.CopyToAsync(gzip);
}
}

protected override bool TryComputeLength(out long length)
{
// Content-Lenght is optional, so set to -1
length = -1;
return false;
}
}

--API调用前进行压缩

string filePath = "SOME FILE PATH";

using (var httpClient = new HttpClient())
{
using (var form = new MultipartFormDataContent())
{
using (var streamContent = new StreamContent(File.OpenRead(filePath)))
{
form.Add(streamContent, "file", Path.GetFileName(filePath));

// Gzip压缩
using (var compressed = new GzipCompressedContent(form))
{
HttpResponseMessage response = httpClient.PostAsync(url, compressed).Result;
}
}
}
}


服务器端在不进行修改的情况下,不能接收到文件,应该是不能自动处理Gzip的Request吧,
所以利用zlib增加了下面的代码

var express = require('express');
var app = express();

function gUnzip(req, res, next) {
var newReq;
if (req.headers['content-encoding'] === 'gzip') {
console.log("received gzipped body");
newReq = req.pipe(zlib.createGunzip());
Object.getOwnPropertyNames(newReq).forEach(function (p) {
req[p] = newReq[p];
});
}
next();
}

app.use(gUnzip);

看log解压缩是跑到了,但文件还是没有收到,

求教
C#压缩的做法对不对?
客户端和服务端哪边有问题,不知道该怎么查了。。。
...全文
11477 点赞 收藏 11
写回复
11 条回复

还没有回复,快来抢沙发~

发动态
发帖子
C#
创建于2007-09-28

8.4w+

社区成员

64.0w+

社区内容

.NET技术 C#
社区公告
暂无公告