2017-08-13 79 views
0

我要上傳文件到這個API https://support.crowdin.com/api/add-file/如何使用restsharp上傳多個文件?

如何創建一個名爲files參數和使用RestSharp添加多個文件呢?

我寫了這段代碼到目前爲止,但它不起作用,RestSharp似乎沒有按預期上傳文件。

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

這給了我

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

@SirRufo您鏈接的問題是關於添加單個文件。這個問題是關於添加一個文件數組,這不是直截了當的。 – riki

+0

有一個用於添加兩個文件的示例的答案(6 upvotes)。 –

+0

答案是將兩個文件直接添加到請求中,而我的情況更復雜。我必須將多個文件添加到名爲「files」的「數組」中。 (所以我需要控制數組名稱)。 – riki

回答

2

@SirRufo在評論中提到的解決方案,但沒有張貼它作爲一個soltion,所以在這裏我要解釋一下。

http POST方法實際上沒有數組的概念。 而是在字段名稱中加上方括號只是一個約定。

此示例代碼工作:

 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 ... 

無需窩自定義參數或任何複雜的那樣。 使用這種「特殊」名稱格式添加文件是它所需要的。

我的錯誤是認爲files[filenamehere.txt]部分意味着比實際需要更復雜的POST機構。