[英]How to compress file data with ICSharpCode.SharpZipLib and upload using HttpClient?
我正在使用 ICSharpCode.SharpZipLib 並執行以下操作:讀取文件內容,壓縮(zlib),然后使用 HttpClient.PostAsync 上傳到服務器
我的常規方法(適用於相應下載)是創建一個壓縮的輸出流,然后從 output 復制/CopyAsync 到 StreamContent。 但是,DeflaterOutputStream 不支持讀取,所以這不起作用。 應該如何有效地進行? 可能只有我一個人,但答案並不明顯。
我知道我可以先將文件壓縮到 memory (即 MemoryStream 或字節數組),然后將它們復制到 http 內容,但這是不可接受的
解決方案是實現 HttpContent 抽象 class,這將提供對 http 主體的 output ZF7B44B3AE7002CB88C246876D9FAA8F8Z 的訪問權限。 需要注意的是,DeflaterOutputStream 將在 dispose 時關閉其輸出流,我們不希望這樣,因此必須將IsStreamOwner
設置為 false。
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
public class ZlibContent : HttpContent
{
private readonly Stream _source;
public ZlibContent(Stream _source)
{
_source = source;
}
protected override async Task SerializeToStreamAsync(Stream destinationStream, TransportContext context)
{
using (var zlibStream = new DeflaterOutputStream(destinationStream) { IsStreamOwner = false })
{
await _source.CopyAsync(zlibStream, this.progress);
}
}
protected override bool TryComputeLength(out long length)
{
length = 0;
return false;
}
}
所以使用它的方式如下:
using (var fileStream = /* open file stream */)
using (var content = new ZlibContent(fileStream))
{
await httpClient.PostAsync("url", content);
}
所以關鍵是當compress-stream(DeflaterOutputStream)在“中間”時,不是從它復制,而是復制到它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.