簡體   English   中英

通過restsharp上傳大於2Gb的文件

[英]Upload file larger than 2Gb by restsharp

我必須上傳大於 2GB 的文件。

我想使用restsharp,但出現錯誤“流太長”。 可以用 resharp 來做,還是我應該使用其他庫?

            var client = new RestClient(url);
            client.ThrowOnDeserializationError = true;
            client.ConfigureWebRequest(x => x.AllowWriteStreamBuffering = false);
            var request = new RestRequest(Method.POST);
            request.AddHeader("X-Auth-Token", token);
            request.AddHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");

            const int chunkSize = 1024; // read the file by chunks of 1KB
            using (var file = File.OpenRead(filePath))
            {
                int bytesRead;
                var buffer = new byte[chunkSize];
                while ((bytesRead = file.Read(buffer, 0, buffer.Length)) > 0)
                {
                    request.AddFileBytes("file", buffer, filePath);
                }
            }


            IRestResponse response = client.Execute(request);
            Console.WriteLine(response.Content);

如果我們在 GitHub 上查看項目,項目中不存在“Stream was too long”文本https://github.com/restsharp/RestSharp

相反,它通常是內存流的例外,其最大大小限制為 2 GB,不幸的是,RestSharp 在一種方法中使用 MemoryStream,但您應該能夠使用另一種方法:

//RestSharp.RestRequest.AddFileBytes:     will not work
/// <inheritdoc />
public IRestRequest AddFileBytes(
    string name,
    byte[] bytes,
    string filename,
    string contentType = "application/x-gzip"
)
{
    long length = bytes.Length;

    return AddFile(
        new FileParameter
        {
            Name          = name,
            FileName      = filename,
            ContentLength = length,
            ContentType   = contentType,
            Writer = s =>
            {
                using var file = new StreamReader(new MemoryStream(bytes));

                file.BaseStream.CopyTo(s);
            }
        }
    );
}

直接使用字節數組應該可以工作,所以使用 AddFile 而不是 AddFileBytes

//RestSharp.RestRequest.AddFile  

/// <inheritdoc />
public IRestRequest AddFile(string name, byte[] bytes, string fileName, string contentType = null)
    => AddFile(FileParameter.Create(name, bytes, fileName, contentType));

public static FileParameter Create(string name, byte[] data, string filename, string? contentType)
    => new() {
            Writer        = s => s.Write(data, 0, data.Length),
            FileName      = filename,
            ContentType   = contentType,
            ContentLength = data.LongLength,
            Name          = name
        };

所以你看到后者使用基流類,這沒有那個限制,因為例如 FileStream deriviate 可以處理更大的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM