I want to post/share an image to server from the iphone. Image is ready to share. I am using the way the most sites shows using the below code
NSData *imageData = UIImageJPEGRepresentation(image, 100);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"0x0hHai1CanHazB0undar135";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding: NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"imageToAttach\"; filename=\"%@\"\r\n",fileName]dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"%@",returnString);
but it is giving me some internal server error, then i pointed it out that the server is demanding stream bytes of the image..How can i convert the image into stream and then post that stream to server ?
Giving the Same Answer 2 Time. How to convert image into binary format in iOS?
You can use the CoreGraphics
' method UIImagePNGRepresentation(UIImage *image)
, which returns NSData
and save it. and if you want to convert it into again UIImage
create it using [UIimage imageWithData:(NSData *data)]
method.
- (void)sendImageToServer {
UIImage *yourImage= [UIImage imageNamed:@"image.png"];
NSData *imageData = UIImagePNGRepresentation(yourImage);
NSString *postLength = [NSString stringWithFormat:@"%d", [imageData length]];
// Init the URLRequest
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"POST"];
[request setURL:[NSURL URLWithString:[NSString stringWithString:@"http://yoururl.domain"]]];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:imageData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
// response data of the request
}
[request release];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With