0

Quick question.

I am trying to do the same as the Curl function as depicted

curl -v -F content=@/home/user/Downloads/test.jpg “http://...:8088/upload?session=(blabla)&conv=(blabla)"

For some reason all my uploads are failing. This is my code.

 // create request

static NSString *boundary = @"---------------------------14737809831466499882746641449";
NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0)];

NSMutableURLRequest *request;
request= [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://%@:8088/upload?session=%@&conv=%@", kQAServer, session , conv]]];
[request setHTTPMethod:@"POST"];


// add header
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@;",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

// add image data
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"content\"; \r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:imageData];
[postbody appendData:[[NSString stringWithFormat:@"--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];


NSURLResponse * response = nil;
NSError * error = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:request
                                      returningResponse:&response
                                                  error:&error];

if (error == nil)
{
    NSString *fileID = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return fileID;
}

return nil;
pnuts
  • 58,317
  • 11
  • 87
  • 139
Legolas
  • 12,145
  • 12
  • 79
  • 132
  • possible duplicate of [ios Upload Image and Text using HTTP POST](http://stackoverflow.com/questions/8564833/ios-upload-image-and-text-using-http-post) – Legolas Feb 19 '14 at 00:43

1 Answers1

0

Don’t use error == nil to check if the command succeeded. The command can fail without an error, and can succeed with one. (This is documented as part of the whole pseudo-protocol for errors.)

Instead just check if you have data or not. If data == nil then you had a hard error, and you should log the error.

(And if you do have data == nil, please post the error and we can help.)

Wil Shipley
  • 9,343
  • 35
  • 59