I am trying to upload a file to a box account using box's HTTP API (not iOS SDK), but for some reason its not working and returning status code 400. What is my mistake in the following code?
NSString *uploadURL = @"https://upload.box.com/api/2.0/files/content";
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *upLoadSession = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:uploadURL]];
[request setHTTPMethod:@"POST"];
[request addValue:[NSString stringWithFormat:@"Bearer %@", @"box_access_token_here"] forHTTPHeaderField:@"Authorization"];
NSString *boundary = @"some_random_boundary_value";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request addValue:contentType forHTTPHeaderField:@"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: form-data; name=\"attributes\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/json\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"'{\"name\":\"%@\", \"parent\":{\"id\":\"%@\"}}'", @"file_name", @"box_folder_id"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: form-data; name=\"file\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", @"mime_type"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:UIImageJPEGRepresentation(someUIImage, 1.0)];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)body.length] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:body];
NSURLSessionUploadTask *uploadTask = [upLoadSession uploadTaskWithRequest:request fromData:body completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(@"%@", error.debugDescription);
} else {
NSLog(@"%@", @"Successfully uploaded");
}
}];
[uploadTask resume];
I'm not sure what is wrong with code but I was getting the same
400 Bad Request
when tried to implement upload in the way it's described here https://box-content.readme.io/#upload-a-file.I ended up replicating behavior that Android sample code uses - and it's somewhat different from what is in API docs:
Please note how
parent_id
andfilename
parts are used - this is quite in contrast to what is advices in API docs.