Reputation: 3
The code below is used to upload image to a remote server, but for a certain reason it does NOT work for me. When I enter, for example to this page and I use the php form to upload image, it works with no problem. So, concerning the PHP part, there is no single problem and everything is working.
What's wrong with that ?
NSData *imageData = UIImageJPEGRepresentation(self.imageViewer.image, 90); NSString *urlString = @"http://example.com/post_image.php"; [request setHTTPMethod:@"POST"]; request = [[NSMutableURLRequest alloc] init]; [request setURL:[NSURL URLWithString:urlString]]; [request setHTTPMethod:@"POST"]; NSString *boundary = @"---------------------------14737809831466499882746641449"; 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:NSUTF8StringEncoding]]; [body appendData:[@"Content-Disposition: form-data; name=\"image\"; filename=\".jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[NSData dataWithData:imageData]]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [request setHTTPBody:body]; NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSString *picture = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; NSLog(@"uploaded picture: %@", picture);
Upvotes: 0
Views: 169
Reputation: 119021
Change the mime type to match what you're actually sending (image/jpeg
).
Delete one of these duplicate lines:
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
(and probably at least log the error parameter...)
Upvotes: 1