iPhone Development: Use POST to submit a form
        Posted  
        
            by Mario
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Mario
        
        
        
        Published on 2010-04-23T14:18:40Z
        Indexed on 
            2010/04/23
            14:23 UTC
        
        
        Read the original article
        Hit count: 356
        
I've got the following html form:
<form method="post" action="http://shk.ecomd.de/up.php" enctype="multipart/form-data">
<input type="hidden" name="id" value="12345" />
<input type="file" name="pic" />
<input type="submit" />
</form>
And the following iPhone SDK Submit method:
- (void)sendfile {
  UIImage *tempImage = [UIImage imageNamed:@"image.jpg"];
  NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
  [request setHTTPMethod:@"POST"];
  [request setURL:[NSURL URLWithString:@"http://url..../form.php"]];
  NSString *boundary = @"------------0xKhTmLbOuNdArY";
  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%@\r\n",boundary] dataUsingEncoding:NSASCIIStringEncoding]];
  [body appendData:[@"Content-Disposition: form-data; name=\"id\"\r\n\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
  [body appendData:[@"12345" dataUsingEncoding:NSUTF8StringEncoding]];
  [body appendData:[[NSString stringWithFormat:@"\r\n%@\r\n",boundary] dataUsingEncoding:NSASCIIStringEncoding]];
  [body appendData:[@"Content-Disposition: form-data; name=\"pic\"; filename=\"photo.png\"\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
  [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
  [body appendData:[NSData dataWithData:UIImageJPEGRepresentation(tempImage, 90)]];
  [body appendData:[[NSString stringWithFormat:@"\r\n%@",boundary] dataUsingEncoding:NSASCIIStringEncoding]];
  // setting the body of the post to the reqeust
  [request setHTTPBody:body];
  NSError *error;
  NSURLResponse *response;
  NSData* result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
  NSString* aStr = [[[NSString alloc] initWithData:result encoding:NSASCIIStringEncoding] autorelease];
  NSLog(@"Result: %@", aStr);
  [request release];    
}
This does not work, but I have no clue why. Can you please help me?!! What am I doing wrong?
© Stack Overflow or respective owner