RestSharp 上传文件无需填充 RAM
RestSharp upload file without fill RAM
This question is not answered yet in Stack Overflow and it's not duplicated
我有一个完全像这样的代码,尝试使用 RestSharp 库上传文件。
问题:
但问题是 上传文件填满了内存 (RAM) 并且在 大文件 上出现错误或错误。
var client = new RestClient("https://example.com/api/");
var request = new RestRequest("file/upload", Method.POST);
string filePath = @"C:\LargeFile.mkv";
client.ConfigureWebRequest(x => x.AllowWriteStreamBuffering = true);
request.AddHeader("Content-Type", "multipart/form-data");
request.AddParameter("access_token", "exampleToken");
request.AddFileBytes("upload_file", File.ReadAllBytes(filePath), Path.GetFileName(filePath), MimeMapping.GetMimeMapping(filePath));
client.ExecuteAsync(request, response =>
{
Console.WriteLine(response.Content);
});
注意:我找不到不填充 RAM 的工作方法,我知道它必须使用流类型或字节数组,但是我做不到。
您需要使用 AddFile
接受流编写器回调的重载:
IRestRequest AddFile(string name, Action<Stream> writer, string fileName, long contentLength, string contentType = null);
它有一个缺点,您必须明确指定文件大小,因为 RestSharp 无法提前知道您将写入流的内容,并且文件大小必须包含在 ContentLength
请求中 header.
当使用流写入器时,您的函数将与请求文件流一起调用,因此您可以只写入它real-time,而无需先将文件加载到内存。
This question is not answered yet in Stack Overflow and it's not duplicated
我有一个完全像这样的代码,尝试使用 RestSharp 库上传文件。
问题:
但问题是 上传文件填满了内存 (RAM) 并且在 大文件 上出现错误或错误。
var client = new RestClient("https://example.com/api/");
var request = new RestRequest("file/upload", Method.POST);
string filePath = @"C:\LargeFile.mkv";
client.ConfigureWebRequest(x => x.AllowWriteStreamBuffering = true);
request.AddHeader("Content-Type", "multipart/form-data");
request.AddParameter("access_token", "exampleToken");
request.AddFileBytes("upload_file", File.ReadAllBytes(filePath), Path.GetFileName(filePath), MimeMapping.GetMimeMapping(filePath));
client.ExecuteAsync(request, response =>
{
Console.WriteLine(response.Content);
});
注意:我找不到不填充 RAM 的工作方法,我知道它必须使用流类型或字节数组,但是我做不到。
您需要使用 AddFile
接受流编写器回调的重载:
IRestRequest AddFile(string name, Action<Stream> writer, string fileName, long contentLength, string contentType = null);
它有一个缺点,您必须明确指定文件大小,因为 RestSharp 无法提前知道您将写入流的内容,并且文件大小必须包含在 ContentLength
请求中 header.
当使用流写入器时,您的函数将与请求文件流一起调用,因此您可以只写入它real-time,而无需先将文件加载到内存。