Image is not uploading into webservice - iphone

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.

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.

JSON parsing, How to get response from server

I have the following details, for get the data from server. What is the use of methodIdentifier and web service name ?
{"zip":"12345","methodIdentifier":"s_dealer"}
url:- http://xxxxxxxxxxxxxxx.com/api.php
method: post
web service name: s_dealer
response : {"success":"0","dealer":[info...]}
I don't know how to send zip number "12345" with the url. Please direct me on right direction. I use the following.
-(void)IconClicked:(NSString *)zipNumber
{
NSString *post = [NSString stringWithFormat:#"&zipNumber=%#",zipNumber];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://xxxxxxxxxxxxxxxxxxx.com/api.php"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn)
{
NSLog(#"Connection Successful");
}
else
{
NSLog(#"Connection could not be made");
}
receivedData = [[NSMutableData alloc]init];
}
when i print the response in console :\"Unexpected end of string\"
Without knowing more about the API, I can't be certain about your requirements, but it seems that the server is expecting the request to contain JSON. The way you currently are creating the body for the request is using standard POST variables.
Have you tried changing:
NSString *post = [NSString stringWithFormat:#"&zipNumber=%#",zipNumber];
to:
NSString *post = [NSString stringWithFormat:#"{\"zip\":\"%#\",\"methodIdentifier\":\"s_dealer\"}",zipNumber];
Regarding your other questions, I'm guessing that there is a single URL for the API. The methodidentifier is used by the server in order to determine which server method(s) to run.
You get this error because you do not get a json as a response, but an error from Apache (or whatever), that has different structure, and json cannot parse it. Try my method to initiate the connection, in order to gain a successful one.
Declare a NSURLConnection property and synthesize it. Now:
NSString *post = [NSString stringWithFormat:#"zipNumber=%#",zipNumber];
NSString *toServer = [NSString stringWithString:#"your server with the last slash character"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#api.php?", toServer]];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *urlRequest = [[[NSMutableURLRequest alloc] init] autorelease];
[urlRequest setURL:url];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlRequest setValue:#"utf-8" forHTTPHeaderField:#"charset"];
[urlRequest setHTTPBody:postData];
[urlRequest setTimeoutInterval:30];
NSURLConnection *tmpConn = [[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self] autorelease];
self.yourConnectionProperty = tmpConn;
Now you work with self.yourConnectionProperty in connection delegates. Cheers!
hey bro check my answer for same problem may help you... You have to use the NSURLConnection Delegates to get the data
Could not make Json Request body from Iphone

converting image to base64 and uploading in JSON format to server

I have a problem. I need to convert base64 string to JSON string and pass it to server.
for example I have a base64 string /9j/4AAQSkZJRgABAQAAAQABAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAACqADAAQAAAABAAAACgAAAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/Z
i need to convert it to JSON format. I do the following:
+(NSData *)prepareForUploading:(NSString *)base64Str
{
NSDictionary *dict=[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:base64str, nil] forKeys:[NSArray arrayWithObjects:#"picture", nil]];
NSData *preparedData=[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
return preparedData;
};
here how I'm making NSURLRequest
-(NSString *)uploadPict:(NSString *)pict
{
NSLog(#"Server: upload: called");
NSData *prepPictData=[[self class] prepareForUploading:pict];
NSString *preparedBase64StrInJSON=[[NSString alloc] initWithData:prepPictData encoding:NSUTF8StringEncoding];
//here I'm adding access token to request
NSString *post = [NSString stringWithFormat:#"accessToken=%#&object=%#", self.key, preparedBase64StrInJSON];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#upload.aspx", serverAPIPath]]];
[request setHTTPMethod:#"POST"];
[request setValue:#"postLength" forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *error;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//....
}
But I get "Invalid length for a Base-64 char array" from server. What's wrong?
If I paste my token and JSON to http://hurl.it/ and make request using it - everything goes normally.
I think the problem is / symbols in base64 string and as a result / symbols in JSON.
Maybe it is something with [postData length]: if I erase \/ characters from JSON string:
9j4AAQSkZJRgABAQAAAQABAAD4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAACqADAAQAAAABAAAACgAAAAD2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQHZ request will perform normally but this base64 encoded string is not the same.
Please, help me to solve this problem
jString is your base64 string, first use following line
[self encodeString:jString];
and then call use following.
NSString *URL = [NSString stringWithFormat:#"forms.asmx/CreateUpdate?"];
URL=[NSString stringWithFormat:#"%#%#", USERS_API_ROOT_URL, URL];
NSString *post = [NSString stringWithFormat:#"apiKey=A0B1I2L3A4L5-A1D3-4F30-5AB2-C8DEE266&strPost=%#",jString];
unsigned long long postLength = [post length];
NSString *contentLength = [NSString stringWithFormat:#"%llu",postLength];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:URL]];
[request setHTTPMethod:#"POST"];
[request setValue:contentLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData ];
(void)[[NSURLConnection alloc] initWithRequest:request delegate:self];
-(NSString *)encodeString:(NSString *)string
{
NSString *newString = (__bridge_transfer NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, NULL,CFSTR(":/?#[]#!$ &'()*+,;=\"<>%{}|\\^~`"), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
return newString;
}
Hope it will work.

how to send audio file through http post to a server from ios?

i have two function recordsound and post this recorded sound to the server.
this is the following code i used to post to the server
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"recordedTmpFile" ofType:#"caf"];
NSURL *file =[[NSURL alloc] initFileURLWithPath:filePath];
NSString *filepath = [[NSBundle mainBundle] initWithContentsOfURL:recordedTmpFile];
NSData *postData = [NSData dataWithContentsOfFile:filePath];
//nsdata to string
NSString* newStr = [NSString stringWithUTF8String:[postData bytes]];
//http post
NSMutableString *jsonRequest = [[NSMutableString alloc]init];
[jsonRequest appendString:newStr];
NSURL *url = [NSURL URLWithString:#"http address"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
[NSURLConnection connectionWithRequest:[request autorelease] delegate:self];
I am using ASIHTTPRequest's library. It has a setFile: method to allow you posting a file to the server.
first of all you have to change the audio file data in binary format then send it in network by http protocol.
Then at server side you have to write a code to accept that binary file then convert it into proper audio file and store it on server.
This is how you can do your task...

How to set the format of JSON post method in iphone

I'm sending a post request through webservices but I'm not getting the response I want.
Here's my code:
NSString *newurlString = [NSString stringWithFormat:#"{\"name\":\"asit\",\"email\":\"m.kulkarni#easternenterprise.com\",\"businessType\":\"1\",\"score\":30}"];
NSString * url = #"http://www.nieuwe-dag.nl/mobile_be/public/?action=saveScore";
//NSString *urlString =[NSString stringWithFormat:#"name=%#&email=%#&businessType=%d&score=%d",name, email, bussinesstype, score];
NSData *postData = [newurlString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSLog(#"urlString::%#",newurlString);
NSLog(#"postLength::%#",postLength);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:300];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *theConnection =[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection){
webData = [[NSMutableData data] retain];
}
else {
NSLog(#"theConnection is NULL");
}
You are setting the request type to json but you are not creating a json. The data you are creating is just nsstring. I think you need to create a json object. You can download JSON API from here:
https://github.com/stig/json-framework/
Use [SBJSONWriter dataWithObject:] to create a JSON object. Then pass it to your request.
FOr more info on JSON:
http://www.json.org/
You need proper postData
NSDictionary *dataDict = #{
#"name": #"asit",
#"email": #"m.kulkarni#easternenterprise.com",
#"businessType": #"1",
#"score": #(30)
};
NSData *postData = [NSJSONSerialization dataWithJSONObject:dataDict options:0 error:nil];