views:

755

answers:

1

Hello! I'd like to know {insert_title_here}?

I use this method, but with no success:

    //string data
    NSString *post = @"message=helloWorld";
    NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

    //file data
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:@"ImageFile.png"];
    NSData *imageData = [[NSData alloc] initWithContentsOfFile:fullPathToFile];

    //request
    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    [request setURL:@"http://www.example.com/"];
    [request setHTTPMethod:@"POST"];
    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    //POST body
    NSMutableData *postbody = [NSMutableData data]; 

    //append string data
    [postbody appendData:postData];

    //append file
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [postbody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"iconFile\"; filename=\"ImageFile.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

   [postbody appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[NSData dataWithData:imageData]];
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [request setHTTPBody:postbody];

    //set content length
    NSString *postLength = [NSString stringWithFormat:@"%d", [postbody length]];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];

    //send and receive
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

Any suggestions?

A: 

It seems like you're attaching a file.

Check http://stackoverflow.com/questions/936855/file-upload-to-http-server-in-iphone-programming.

KennyTM
Yes, thanks, i found this post with ASIHTTPRequest mentioned just some 10 minutes ago ;]
hveveris