How to upload multiple files with restsharp? [duplicate]

醉酒当歌 提交于 2019-12-29 09:25:11

问题


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

How can I create a parameter named files and add multiple files to it using RestSharp?

I wrote this code so far but it doesn't work, RestSharp does not seem to upload the file as intended.

        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);

This gives me

{
  "success":false,
  "error":{
    "code":4,
    "message":"No files specified in request"
  }
}

回答1:


@SirRufo mentioned the solution in the comments but didn't post it as a soltion, so I'll explain it here.

The http POST method actually has no concept of arrays. Instead having square brackets in the field names is just a convention.

This example 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 nest custom parameters or anything complicated like that. Adding the files with this "special" name format is all it takes.

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



来源:https://stackoverflow.com/questions/45665682/how-to-upload-multiple-files-with-restsharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!