rishabh
rishabh

Reputation: 1165

Box File Upload API using Objective C

I have been trying out for a while using Box 2.0 API to upload a file from Objective C client to my Box folder. I've read a few posts from:

I've tried successfully using the Curl, as mentioned in the documentation, but always get a 404 when trying to create a NSMutableUrlRequest. This is my code:

NSURL *URL = [NSURL URLWithString:@"https://api.box.com/2.0/files/content"];
    urlRequest = [[NSMutableURLRequest alloc]
                  initWithURL:URL cachePolicy:NSURLRequestReloadIgnoringCacheData
                  timeoutInterval:30];
    [urlRequest setHTTPMethod:@"POST"];
    AppDelegate *appDelegate = [AppDelegate sharedDelegate];
    NSString *p = [NSString stringWithFormat:@"BoxAuth api_key=%@&auth_token=%@",API_KEY,appDelegate.boxAuthToken];
    [urlRequest setValue:p forHTTPHeaderField:@"Authorization"];
    [urlRequest setValue:@"multipart/form-data, boundary=AaB03x" forHTTPHeaderField:@"Content-Type"];

    NSString *postBody = @"--AaB03x"
            @"content-disposition: form-data; name=\"filename\"; filename=\"test.txt\";"
            @"folder_id=466838434"
            @"Content-type: text/plain"
            @""
            @"testing box api 2.0"
            @""
            @"--AaB03x--";

    NSData *data = [postBody dataUsingEncoding:NSUTF8StringEncoding];
    [urlRequest setHTTPBody:data];
    [urlRequest setValue:[NSString stringWithFormat:@"%d",[data length]] forHTTPHeaderField:@"Content-Length"];

Upvotes: 1

Views: 533

Answers (2)

Vova Galchenko
Vova Galchenko

Reputation: 79

There are a couple of problems that I see with the way you're constructing the postBody. Having newlines between string literals in your code simply concatenates them. You actually need to have carriage return and line feed to separate different parts of your HTTP body. Also, you mashed both of your form elements in one. The file and folder_id are two separate form elements. You could try something like this:

NSString *postBody = @"\r\n--AaB03x\r\n"
                      "Content-Disposition: form-data; filename=\"test.txt\"\r\n"
                      "Content-Type: text/plain\r\n\r\n"
                      "testing box api 2.0"
                      "\r\n--AaB03x\r\n"
                      "Content-Disposition: form-data; name=\"folder_id\";\r\n\r\n"
                      "0"
                      "\r\n--AaB03x--\r\n\r\n";

I think that should work provided everything else is set up properly.

Upvotes: 3

Max Woolf
Max Woolf

Reputation: 4058

Use http://allseeing-i.com/ASIHTTPRequest/

It makes dealing with multipart forms much easier!

Upvotes: 0

Related Questions