Send image to server as binary data - iphone

I want to make an iPhone application to send an image to my server.
I want to draw something in iPhone (ex: a signature) as an image to POST binary image to my server (server is JSP). Please tell me what I have to do?
how to use iPhone UI?
how to make binary data from image, etc.

Firstly you can get an NSData object containing either a PNG or JPEG representation of the image data using the UIImagePNGRepresentation and UIImageJPEGRepresentation functions.
// To get the data from a PNG file
NSData *dataForPNGFile = UIImagePNGRepresentation(yourImage);
// To get the data from a JPEG file
NSData *dataForPNGFile = UIImageJPEGRepresentation(yourImage, 0.9f);
(for more information see: UIImage Class Reference)
To finish to upload data from your iPhone to your server you can do this:
- (void)sendImage {
NSData *postData = [nsdata from your original image];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
// Init and set fields of 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:postData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
// Return data of the request
NSData *receivedData = [[NSMutableData data] retain];
}
[request release];
}

Use the drawrect method to do signatures on an UIImage. For that you have to use a UITouch delegate
and use the following to convert your UIImage object to NSData
// To get the data from a PNG file
NSData *dataForPNGFile = UIImagePNGRepresentation(yourImage);
// To get the data from a JPEG file
NSData *dataForPNGFile = UIImageJPEGRepresentation(yourImage, 0.9f);

Related

Not able to upload UIImage to server in iOS

I have been trying to upload UIImage on the server,but before uploading i have been converting it to BASE64 string.The method is POST and i am sending the image with other parameters in body.Have read several answers related to this but didn't get anything useful.
Here is my code
-(void)makeprofileWithData:(NSString *)urlstring andname:(NSString *)name gender:(NSString *)gender withstatus:(NSString *)status latitide:(NSString *)lat withLongitude:(NSString *)longitude andaddress:(NSString *)address andImage:(NSString *)string;
{
appdel=(AppDelegate *)[UIApplication sharedApplication].delegate;
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#",appdel.bseurl,urlstring]];
receivedData = [[NSMutableData alloc] initWithLength:0];
NSString *tempString=[NSString stringWithFormat:#"mobile=%#&name=%#&gender=%#&status=%#&address=%#&latitude=%#&longitude=%#&profile_pic=%#",[[NSUserDefaults standardUserDefaults]objectForKey:#"mobile"],name,gender,status,address,lat,longitude,string];
NSData *requestData = [tempString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
[NSURLConnection connectionWithRequest: request delegate:self];
}
In this method the string is the BASE64 string,and i am sending other parameters like mobile,name location,address ,gender also in the body separated by &.
I suggest instead of BASE64 conversion you can use GZiP Compression. It will give better result. You can download sample project from here
Here
You can use GZIP class from Compression and uncompression.
I think there may be a problem with your UTF8 encoding; can you check the result of
- (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding
in your code to clear away that possibility.

Image is not uploading into webservice

I want to upload an image into webservice, but when i upload it only name of the image is saving, but not image.
Please find the code and images for your reference.
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[self dismissModalViewControllerAnimated:YES];
NSData *image = UIImageJPEGRepresentation([info objectForKey:UIImagePickerControllerOriginalImage], 0.1);
NSMutableString *urlString = [[NSMutableString alloc] initWithFormat:#"name=thefile&&filename=recording"];
[urlString appendFormat:#"%#", image];
NSData *postData = [urlString dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSString *baseurl = #"http://192.168.2.34/Service1.svc/upload/filename.png";
NSURL *url = [NSURL URLWithString:baseurl];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setHTTPMethod: #"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setValue:#"application/x-www-form-urlencoded"
forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPBody:postData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
[connection start];
NSLog(#"Started!");
}
after uploading image and name of the image appears as below:
But when i open the image is show nil.
i am not sure what is going wrong..kindly help me.
Thanks in advance.
These lines are wrong:
NSData *image = UIImageJPEGRepresentation([info objectForKey:UIImagePickerControllerOriginalImage], 0.1);
NSMutableString *urlString = [[NSMutableString alloc] initWithFormat:#"name=thefile&&filename=recording"];
[urlString appendFormat:#"%#", image];
NSData *postData = [urlString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
...
[urlRequest setValue:#"application/x-www-form-urlencoded"
forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPBody:postData];
Replace with:
NSData *image = UIImageJPEGRepresentation([info objectForKey:UIImagePickerControllerOriginalImage], 0.1);
...
[urlRequest setHTTPBody:image];
Also you should probably change 0.1 to 0.8 or something, or else the quality will be terrible.
You will also need to make sure the server is correctly reading the data. This depends what you are using server side... in PHP this is how you do it:
$data = file_get_contents('php://input');
file_put_contents($data, 'filename.jpg');
The problem is in:
[urlString appendFormat:#"%#", image];
You are linking the description of the NSData object in the post data and this is an error.
To upload a binary file you need to serialize your data or use a multipart/form-data POST request.
These are the 2 solutions:
1) Convert image NSData in Base64 with this category (tested)
https://github.com/l4u/NSData-Base64
and then do
[urlString appendFormat:#"&image=%#", [image base64EncodedString]];
You need to convert on the server the base64 data back using (in PHP)
http://www.php.net/manual/en/function.base64-decode.php
2) Implement
File Upload to HTTP server in iphone programming
I hope this helps.

Failed To Send Json With NSUrlconnection

i am implementing this code wich take apple in app purchase receipt from the current transaction (not listed here) i am converting it to base64 NSData object, create new NSString with the values and keys (json object) and send it trough NSUrlconnection .
when the compiler hits the init with request the app crashes after 2 seconeds...
without to get any response. this is the code.
NSData *data = [NSData dataFromBase64String:receiptStr];
NSString *jsonString = [NSString stringWithFormat:#"{\"receipt-data\":\"(%#)\",\"password\":\"(%#)\"}", data, SHARED_SECRET];
NSLog(#"%#",jsonString);
savedReceipt = jsonString;
[[NSUserDefaults standardUserDefaults]setValue:savedReceipt forKey:#"savedrecipt"];
[[NSUserDefaults standardUserDefaults]synchronize];
NSData *requestdata = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; //urlData = [[NSMutableData data] retain];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://sandbox.itunes.apple.com/verifyReceipt"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[NSString stringWithFormat:#"%#",requestdata]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
anyone have an idea what am i doing wrong?
i am also new to json so it could be also a problem there.
That's because this line in your code:
[request setHTTPBody:[NSString stringWithFormat:#"%#",requestdata]];
Is trying to setHTTPBody to some formatted NSString, when the method is actually expecting NSData.
Just use:
[request setHTTPBody: requestdata];
And see if you have better results.

upload image to server

i want to upload an
UIImage
to a server.
the problem i dont know how to add it to my post to the server.
until now i sent post with thia:
NSString *reqURL = [NSString stringWithFormat:#"url"];
reqURL = [reqURL stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:reqURL]];
NSURLResponse *resp = nil;
NSError *err = nil;
NSData *response = [NSURLConnection sendSynchronousRequest: theRequest returningResponse: &resp error: &err];
there is any different way to do for image?
Use ASIHttpRequest
-(void)uploadImage{
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
// Upload a file on disk
[request setFile:#"/Users/ben/Desktop/ben.jpg" withFileName:#"myphoto.jpg" andContentType:#"image/jpeg"
forKey:#"photo"];
// Upload an NSData instance
[request setData:UIImageJPEGRepresentation(myUIImage) withFileName:#"myphoto.jpg" andContentType:#"image/jpeg" forKey:#"photo"];
[request setDelegate:self];
[request setDidFinishSelector:#selector(uploadRequestFinished:)];
[request setDidFailSelector:#selector(uploadRequestFailed:)];
[request startAsynchronous];
}
This answer points to this wrapper framework that should make it easy to do what you want without dealing with HTTP header strings and so on.
Basically, you'll turn your UIImage into an NSData object using a function like UIImagePNGRepresentation() and then upload it over HTTP.

FTP upload iphone sdk

I need to upload a single file. I have tried ASIRequest or whatever it is called, but would like to have something with a detailed guide.
You'll want to use ASIFormDataRequest. You'll send your file as an NSData object in the request. Here's an example of sending a JPEG. If you have some other file type, you'll need to convert it to an NSData object for transmission to the server.
NSString *filename = #"image.jpg";
UIImage *image = [UIImage imageNamed:#"image.jpg"];
NSData *fileData = UIImageJPEGRepresentation(image, 0.9);
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL urlWithString:#"http://www.yoursite.com"]];
[request setPostValue:filename forKey:#"name"];
[request setData:fileData forKey:#"file"];
[request setTimeOutSeconds:500];
[request setRequestMethod:#"POST"];
[request startSynchronous];
// handle response from server
The ASI docs go over this in the section titled "Sending a form POST with ASIFormDataRequest" - http://allseeing-i.com/ASIHTTPRequest/How-to-use