简体   繁体   English

Webclient将文件上传到Box的API v2

[英]Upload file to API v2 of Box by Webclient

I'm working with the Box API v2, I've try to do the upload file with the WebClient but without success. 我正在使用Box API v2,但我尝试使用WebClient进行上传文件,但未成功。

From the API: 从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 file=@myfile.jpg

So I've write it by C#: 所以我用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. 当我尝试调试以查看发生了什么时,在UploadValues步骤中什么也没看到。

Any idea? 任何想法? Thank you! 谢谢!

Okay, finally I solved the upload problem with HttpClient and MultipartFormDataContent, here is final code to upload a text file: 好的,最后我用HttpClient和MultipartFormDataContent解决了上传问题,这是上传文本文件的最终代码:

        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. 然后sContent将是json,其中包含上传文件的详细信息。 Hope this help! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM