Sending images as part of form data from an iPhone - ios

I've managed to get simple text data sent to a server using this code:
NSMutableString *parameterString = [[NSMutableString alloc] initWithString: #""];
[parameterString appendString:#"name=steve&"];
[parameterString appendString:#"surname=jobs&"];
[parameterString appendString:#"age=55"];
NSURL *url = [NSURL URLWithString:#"http://example.come/script/"];
request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
NSData *parameterData = [parameterString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:parameterData];
With that I can send text form data. But how can I send PNG images as well?

You could just convert the image to an NSData object, then base64 encode it to send it as a parameter.
Base64 encoding examples found here: How do I do base64 encoding on iphone-sdk?

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addData:imageData withFileName:#"image.png" andContentType:#"image/png" forKey:#"yourParamKey"];

Related

Upload to .NET web service iOS

I need to pass some data in order for the server to the save the info,in order to do this the parameters need to pass the parameters in XML nodes following a url http://xxx.xxx.xx.xxx/WCF/Service1.svc/XXX/Upload?sXML=
Here is an example of the XML node structure
<Send_info>
<Service_order>
</Service_order>
<Data_stream>
<info>
</info>
</Data_stream>
</Send_info>.
The return value would be a JSON string with {"Uploaded":"TRUE"} or {"Uploaded":"FALSE"} respectively.
I have tried this method with no answer it just return nil.
-(void)Request:(NSData*)data{
NSURL *aUrl = [NSURL URLWithString:#"http://xxx.xxx.xx.xxx/WCF/Service1.svc/XXX/Upload?sXML="];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:#"GET"];
[request setHTTPBody:data];
NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
edit:you can find the answer in the comments
The answer was quite simple just use these blocks of code and substitute them with your own parameters
POST:
-(void)webservicepost:(NSString *)poststring{
NSString *poststring = #"String in the format we need to upload";
NSURL *remoteURL = [NSURL URLWithString:#"URL in which we'll upload"];
NSMutableURLRequest *Request = [[NSMutableURLRequest alloc] initWithURL:remoteURL];
[Request addValue:#"application/json; charset=utf-8" forHTTPHeaderField: #"Content-Type"];//Formats for the data
NSMutableData *body = [NSMutableData data];
[body appendData:[poststring dataUsingEncoding:NSUTF8StringEncoding]]; //Add content and coding
[Request setHTTPMethod:#"POST"]; //POST method
[Request setHTTPBody:body];
NSData *data = [NSURLConnection sendSynchronousRequest:Request returningResponse:nil error:nil];//Server response in data form
NSString *sdata = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];//Server response in string form
}
GET:
-(void)get:(NSString *)myxmlstring{
NSString *escapedString = [myxmlstring stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *urlString = [NSString stringWithFormat:#"http://xxx.xxx.xx.xxx/WCF/Service1.svc/XXX/Upload?sXML=%#",escapedString];
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSURLConnection sendSynchronousRequest:Request returningResponse:nil error:nil];//Server response in data form
NSString *sdata = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];//Server response in string form
//FROM HERE YOU CAN USE THE RETRIEVED INFORMATION FROM THE URL
}

iOS - How to send attachment using SOAP?

I am using NSMutableURLRequest to upload parameters to server using SOAP API and it is working fine.
static NSString *URLString = #"http://www.myURL";
NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:[NSURL URLString]];
[request addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request addValue:#"http://..." forHTTPHeaderField:#"SOAPAction"];
NSString *name = #"John";
NSString *parameters = [NSString stringWithFormat:
#"<s:Envelope xmlns:s=\"http://..../\">\n"
"<s:Body >\n"
"<name>%#</name>\n"
"</s:Body>\n"
"</s:Envelope>\n", name];
[request setHTTPBody:[parameters dataUsingEncoding:NSUTF8StringEncoding]];
_myConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Now I want to send a text file (attachment) along with the parameters.
Can someone help?
Hi you can convert your file into NSDATA then into BASE64 String and add as parameter to your request body and after that at backend you can convert BASE64 String to Binary Data and save it as text file.
Encoding
NSString *str=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"file.txt"];
NSData *data = [NSData dataWithContentsOfFile:str];
NSString *base64String = [data base64EncodedStringWithOptions:0];
NSLog(#"%#", base64String);
Here is the link for BASE64 Conversion classes
Just add one more parameter
NSString *parameters = [NSString stringWithFormat:
#"<s:Envelope xmlns:s=\"http://..../\">\n"
"<s:Body >\n"
"<name>%#</name>\n"
"<fileData>%#</fileData>\n" //Here is new parameter
"</GetChanges>\n"
"</s:Body>\n"
"</s:Envelope>\n", name, base64String];

How to upload String and Image using ASIFormDataRequest?

I want to upload follow Log Strings along with UIImage,
HOw can I achieve such objective????
I can see to send only image , but i want to send image along with text data using this ASIFormDataRequest, using POST request type.
NSLog(#"data is here %#\n%#\n%#\n%#\n%#\n",deviceID, postID, name, message, picture);
UIImage *image= [UIImage imageNamed:#"profile_avatar.png"];
NSString *strURL = #"https://abc.abc.com/comments/create";
// ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:strURL]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:strURL]]; // Upload a file on disk
// NSString *filename1=[NSString stringWithFormat:#"friendship.jpg"];
UIImage *image1=image;
NSData *imageData1=UIImageJPEGRepresentation(image1, 1.0);
[request setData:imageData1 withFileName:#"filename" andContentType:#"image/png" forKey:#"avatar"];
[request setRequestMethod:#"POST"];
[request addRequestHeader:#"Authorization" value:[NSString stringWithFormat:#"Basic %#",[ASIHTTPRequest base64forData:[[NSString stringWithFormat:#"username123:pass123"] dataUsingEncoding:NSUTF8StringEncoding]]]];
[request setValidatesSecureCertificate:NO];
//[request appendPostData:body];
[request setDelegate:self];
[request setTimeOutSeconds:3.0];
request.shouldAttemptPersistentConnection = NO;
[request setDidFinishSelector:#selector(uploadRequestFinished:)];
[request setDidFailSelector:#selector(uploadRequestFailed:)];
[request startAsynchronous];
Thanks
There is one method available to send parameter as well
[request setPostValue:#"YourValue" forKey:#"YourKey"];

Seems like by uiimage encoding is altered before POST request

I'm currently working on sending uiimages to my server to be stored on the server. So I get an image from the user gallery and then encode it using Base64 and then send it to my server. However all the images I sent to my server don't show. I'm wondering whether the post request I make with the base64encodedstring alters the encoded string.
Here is what I have done.
//Upload picture to server
NSData *imageData=UIImageJPEGRepresentation(showPic.image, 1.0f);
NSLog(#"The size of the image is %i",[imageData length]);
[Base64 initialize];
NSString *strEncoded = [Base64 encode:imageData];
//NSLog(#"This is the encoded string to be uploaded %#",encodedPic);
prefs=[NSUserDefaults standardUserDefaults];
userid=[prefs stringForKey:#"userid"];
NSLog(#" %# is the userid to be used to upload the pic",userid);
NSString *poster = #"username=";
poster = [poster stringByAppendingString:userid];
poster = [poster stringByAppendingString:#"&image="];
poster = [poster stringByAppendingString:strEncoded];
NSString *post = poster;
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.example.com/server/upload"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[[NSURLConnection alloc] initWithRequest:request delegate:self];

IOS: ASIFormDataRequest with quotation marks

I have to send json to a web service that only accepts it via a POST variable.
ASIFormDataRequest insists on escaping my quotation marks.
any help would be appreciated
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
NSString *body = [NSString stringWithFormat:#"{\"user\":\"username\",\"pass\":\"password\"}"];
[request setPostValue:body forKey:#"body"];
[request startSynchronous];
output: "{\"user\":\"username\",\"pass\":\"password\"}"
Try Converting the parameter into JSON representation before sending it through SBJSON or whatever JSON parser you are using.
JosephH is right
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request appendPostData:[dataString dataUsingEncoding:NSUTF8StringEncoding]];
[request setRequestMethod:#"POST"];
[request startSynchronous];
was the way to go.

Resources