This question is not answered yet in Stack Overflow and it's not duplicated
I have a code exactly like this, try to upload files with RestSharp library.
Problem :
But the problem is upload files fill the memory (RAM) and it's bad or got error on large files.
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);
});
Note: I don't find a working way to do this without filling RAM, I know that it must use stream types or byte arrays, but I can't do it.
You need to use the AddFile
overload that accepts the stream writer callback:
IRestRequest AddFile(string name, Action<Stream> writer, string fileName, long contentLength, string contentType = null);
It has a drawback that you must specify the file size explicitly because there's no way for RestSharp to know in advance what you will write to the stream and the file size must be included to the ContentLength
request header.
When using the stream writer, your function will be called with the request file stream, so you can just write to it real-time, without loading the file to memory first.