1

I am trying to upload a file to box based on the api here: https://developers.box.com/docs/#files-upload-a-file, and I always get a "bad request" error.

Where is the problem?

url = https://upload.box.com/api/2.0/files/content
data = {"name":"1.jpg","parent":{"id":"0"}}

        private Stream postToUrl(string url, string data)
        {
                WebRequest request = WebRequest.Create(url);
                request.Method = WebRequestMethods.Http.Post;
                byte[] byteArray = Encoding.UTF8.GetBytes(data);
                request.ContentType = "multipart/form-data";
                request.ContentLength = byteArray.Length;
                request.Headers.Add("Authorization", "Bearer " + AccessToken); 
                Stream dataStream = request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();
                WebResponse response = request.GetResponse();

                dataStream = response.GetResponseStream();

            return dataStream;
        }  

I also tried to use the url: https://upload.box.com/api/2.0/files/content?access_token=AccessToken
instead of the Token inside the header

user990635
  • 3,979
  • 13
  • 45
  • 66
  • Where are you specifying the required `name` and `parent` attributes? – tufelkinder Dec 04 '14 at 00:42
  • Outside of the function, I wrote the exact values that I get in "data" and "url" parameters. The file name is "1.jpg", and I'm uploading it to the root folder (id=0). – user990635 Dec 04 '14 at 10:22
  • I do it that way: "{\"name\":\"" + fileName + "\",\"parent\":{\"id\":\"" + destinationFolderId + "\"}}" – user990635 Dec 04 '14 at 10:24
  • Sorry, then where is your function reading and submitting the actual file data? – tufelkinder Dec 04 '14 at 17:20
  • @tufelkinder I want to get a stream and then fill it outside. Is this possible? – user990635 Dec 11 '14 at 14:09
  • I believe the file data and attributes need to be submitted simultaneously as part of the multipart request. See Greg's answer below. An SDK should save you a lot of hassle. – tufelkinder Dec 11 '14 at 18:28

1 Answers1

2

File uploads should be a multipart request, but it looks like your body is JSON. I also don't see where you're setting the file's content.

This answer gives a good example of what a multipart request should look like. The easiest solution is to either use the SDK or find a library that can create a multipart request for you.

Community
  • 1
  • 1
Greg
  • 3,731
  • 1
  • 29
  • 25