Reputation: 2093
I'm working with the Box API v2, I've try to do the upload file with the WebClient but without success.
From the API:
curl https://upload.box.com/api/2.0/files/content \
-H "Authorization: Bearer ACCESS_TOKEN" -X POST \
-F attributes='{"name":"tigers.jpeg", "parent":{"id":"11446498"}}' \
-F [email protected]
So I've write it by C#:
using (WebClient client = new WebClient())
{
client.Headers.Add("Authorization", "Bearer " + Utils.GetAccessTokenFromFile());
client.Headers.Set("Content-Type", "multipart/form-data; boundary=-handeptrai---");
NameValueCollection values = new NameValueCollection() {
{"attributes","{\"name\":\"test.txt\", \"parent\":{\"id\":\"0\"}}"},
{"file",@Utils.TestFilePath}
};
byte[] result = client.UploadValues("https://upload.box.com/api/2.0/files/content", "POST", values);
string json = Encoding.UTF8.GetString(result);
}
When I try to debug to see what is going on, I saw nothing at the UploadValues step.
Any idea? Thank you!
Upvotes: 0
Views: 1129
Reputation: 2093
Okay, finally I solved the upload problem with HttpClient and MultipartFormDataContent, here is final code to upload a text file:
var client = new HttpClient();
var content = new MultipartFormDataContent();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + Utils.GetAccessTokenFromFile());
content.Add(new StreamContent(File.Open(Utils.AnyFilePath, FileMode.Open)), "token", "test.txt");
content.Add(new StringContent("{\"name\":\"test.txt\", \"parent\":{\"id\":\"0\"}}"), "attributes");
var result = await client.PostAsync("https://upload.box.com/api/2.0/files/content", content);
result.EnsureSuccessStatusCode();
string sContent = await result.Content.ReadAsStringAsync();
Then the sContent will be the json which contain details of uploaded file. Hope this help!
Upvotes: 2