How to upload multiple files using restsharp?

I want to upload files to this api https://support.crowdin.com/api/add-file/

How to create a parameter named files and add several files to it using RestSharp?

I have written this code so far, but it does not work, RestSharp does not seem to download the file as it sees fit.

  var addUrl = new Uri($"https://api.crowdin.com/api/project/{projectIdentifier}/add-file?key={projectKey}&json="); var restClient = new RestSharp.RestClient("https://api.crowdin.com"); var request = new RestSharp.RestRequest($"api/project/{projectIdentifier}/add-file", RestSharp.Method.POST); request.AlwaysMultipartFormData = true; request.AddQueryParameter("key", projectKey); request.AddQueryParameter("json", ""); var files = new Dictionary<string, byte[]> { { "testfile", File.ReadAllBytes(fileName) } }; request.AddParameter("files", files, RestSharp.ParameterType.RequestBody); var restResponse = restClient.Execute(request); 

It gives me

 { "success":false, "error":{ "code":4, "message":"No files specified in request" } } 
0
source share
1 answer

@SirRufo mentioned the solution in the comments, but did not post it as soltion, so I will explain it here.

The http POST method doesn't really have a clue about arrays. Instead of having square brackets in the field names, this is just a convention.

This sample code works:

  var restClient = new RestSharp.RestClient("https://api.crowdin.com"); var request = new RestSharp.RestRequest($"api/project/{projectIdentifier}/add-file", RestSharp.Method.POST); request.AlwaysMultipartFormData = true; request.AddHeader("Content-Type", "multipart/form-data"); request.AddQueryParameter("key", projectKey); request.AddQueryParameter("json", ""); request.AddFile("files[testfile1.pot]", fileName); request.AddFile("files[testfile2.pot]", fileName); // Just Execute(...) is missing ... 

No need to embed custom parameters or anything like that. Adding files with this β€œspecial” name is all that is required.

My mistake was that the files[filenamehere.txt] implied a more complex POST body than it really needed.

+2
source

All Articles