How to upload image to a url using post request asynchronously? - iphone

I have to upload an image to a specific url. The specifications that I have to follow are these:
1. Method should be post
2. Image must be uploaded using multipart HTTP content type
3. The name of the HTTP field should be “uploadingTheFile”.
4. Multipart data shiuld have filename.
5. Image content type should be among following-jpeg,jpg,png,gif
I want to upload using NSURLConnection asynchronously. I think I am not able to set the parameters in the request in a proper way.I am getting status code as 200 which suggests that there is no problem with my NSURLConnection delegate methods. The code that I am trying is :
NSString *stringBoundary=#"0xKhTmLbOuNdArY";
// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:url]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"multipart/form-data; boundary=%#",stringBoundary] forHTTPHeaderField:#"uploadfile"];
NSMutableData *postBody = [NSMutableData data];
NSData *imageData=UIImagePNGRepresentation([UIImage imageNamed:#"IMG_0215.JPG"]);
//[postBody appendData:imageData];
[postBody appendData:[#"Content-Disposition: form-data; name=\"data;filename=\"media.png\"\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[NSData dataWithData:imageData]];
[postBody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postBody];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection) {
self.data = [NSMutableData data];
}

I am using following code and it is working fine for me.
NSData *imageData = UIImageJPEGRepresentation(empImgView.image, 90); // convert image in NSData
NSString *urlString = #"http://abc.com/saveimage/Default.aspx"; // your url
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = [NSString stringWithString:#"---------------------------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]];
NSString *imgNameString = [NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#.jpg\"\r\n",[responseSrting substringWithRange:NSMakeRange(1, responseSrting.length - 2)]];
[body appendData:[[NSString stringWithString:imgNameString] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"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];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#",returnString);

Here you can learn how to use afnetworking for upload images
https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ

You can use AFNetworking (it is opensource), here is code that worked for me. This is for AFNetworking 3.0 version.
NSString *serverUrl = [NSString stringWithFormat:#"http://www.yoursite.com/uploadlink", profile.host];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:#"POST" URLString:serverUrl parameters:nil error:nil];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSURL *filePath = [NSURL fileURLWithPath:[url path]];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
LLog(#"progres increase... %# , fraction: %f", uploadProgress.debugDescription, uploadProgress.fractionCompleted);
});
} completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"Success: %# %#", response, responseObject);
}
}];
[uploadTask resume];

Related

How to POST an audio file via NSURLConnection iPhone?

I tried a dozen things. But am not receiving results. I want to convert an audio file wav/mp3 to byte array or otherwise and send it to a php server. Following are few things i tried that are already listed in SO. please help.
NSURL *urlPath = [NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource:#"r2d2" ofType:#"mp3"]];
NSString *wavbundlepath = [urlPath absoluteString];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:wavbundlepath]];
NSUInteger len = data.length;
int8_t *bytes = (int8_t *)[data bytes];
NSMutableString *result = [NSMutableString stringWithCapacity:len];
[result appendString:#"["];
for (NSUInteger i = 0; i < len; i++) {
if (i) {
[result appendString:#","];
}
[result appendFormat:#"%d", bytes[i]];
}
[result appendString:#"]"];
NSString *urlString = #"http://apps2.mobiiworld.com/staging/krafttesting/";
// setting up the request object now
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSData* dataSend = [result dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:dataSend];
NSURLResponse *response;
NSError *err;
NSData *responseData2 = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(#"responseData: %#", responseData2);
next
NSURL *urlPath = [NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource:#"r2d2" ofType:#"mp3"]];
NSString *wavbundlepath = [urlPath absoluteString];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:wavbundlepath]];NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
/*
add some header info now
we always need a boundary when we post a file
also we need to set the content type
You might want to generate a random boundary.. this is just the same
as my output from wireshark on a valid html post
*/
NSString *boundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
/*
now lets create the body of the post
*/
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *filename = #"file";
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\";filename=\"%#\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
// NSLog([NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\";filename=\"%#\"\r\n", filename]);
//[body appendData:[[NSString stringWithString:#"test"] dataUsingEncoding:NSUTF8StringEncoding]];
//[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:data]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// now lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Return : %#", returnString);
The php developer says that he is not receiving any data whatsoever. And he has echoed whatever he receives, but i find a Null string in response. Can anyone please suggest what to do?
This is how i am doing it
NSData *audioData = Here comes your NSData;
NSString *urlString = #"The url of php file";
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[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:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\".caf\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:audioData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(#"Length : %d", returnData.length);
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Return String %#", returnString);
There is another way via ASIHTTPRequest
NSURL *url = [NSURL URLWithString:#"the url comes here"];
ASIFormDataRequest *formRequest = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
NSData *imageData = UIImageJPEGRepresentation([self scaleAndRotateImage:self.m_ImageViewProfile.image], 90);
NSLog(#"Size : %d", imageData.length);
[formRequest setTimeOutSeconds:600];
[formRequest setPostValue:#"If there is any"] forKey:#"the key"];
[formRequest setData:imageData withFileName:#"myphoto.jpg" andContentType:#"image/jpeg" forKey:#"filename"];
//[formRequest setUploadProgressDelegate:progressView];
[formRequest setCompletionBlock:^{
NSString *responseString = [formRequest responseString];
NSLog(#"Response: %#", responseString);
}];
[formRequest setFailedBlock:^{
NSError *error = [formRequest error];
NSLog(#"Error: %#", error.localizedDescription);
}];
[formRequest startSynchronous];
See if it is what you want

Upload pdf data to server

I want to send my pdf file data do server with some user data also like userId and fileName.
I have tried 2 solutions but not got the pdf file on backend. Even i am having the pdf file in my document directory and it is opening successfully.
Tried 1:
-(void)uploadDock{
NSString *fileName =[NSString stringWithFormat: #"%#.pdf",#"Inspection"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:fileName];
NSData *data=[NSData dataWithContentsOfFile:path];
NSString *content=[data base64EncodedString];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
if ([self.responseData retainCount]) {
NSLog(#"Do nothing");
[self.responseData release];
}
self.responseData=[[NSMutableData alloc]init];
NSURL *url = [NSURL URLWithString:#"http://abcgroup.delivery-projects.com:81/api/index.php?keyword=docinsert"];
//self.request = [NSMutableURLRequest requestWithURL:url
//cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
self.request = [NSMutableURLRequest requestWithURL:url];
NSLog(#"Requst %#",request);
NSString *userid=[userDefaults valueForKey:#"UIDD"];
NSString *title=fileName;
NSString *docname=fileName;
NSString *size=[NSString stringWithFormat:#"%d",[data length]];
NSString *post = [NSString stringWithFormat:#"userid=%#&title=%#&docname=%#&size=%#&content=%#",userid,title,docname,size,content];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
[self.request setHTTPMethod:#"POST"];
//NSString *POSTBoundary = [NSString stringWithFormat:#"0xKhTmLbOuNdArY"];
//[self.request addValue:[NSString stringWithFormat:#"multipart/form-data; boundary=%#\r\n", POSTBoundary] forHTTPHeaderField:#"Content-Type"];
[self.request setValue:[NSString stringWithFormat:#"%d", postData.length] forHTTPHeaderField:#"Content-Length"];
[self.request setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[self.request setHTTPBody:postData];
[NSURLConnection connectionWithRequest:self.request delegate:self];
}
Tried 2:
I am reading the NSData of pdf file from Document directory.
/////
-(void)uploadDock{
self.condition=3;
NSString *fileName =[NSString stringWithFormat: #"%#.pdf",#"Inspection"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:fileName];
NSData *data=[NSData dataWithContentsOfFile:path];
NSString *content=[data base64EncodedString];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
if ([self.responseData retainCount]) {
NSLog(#"Do nothing");
}
else{
self.responseData=[[NSMutableData alloc]init];
}
NSURL *url = [NSURL URLWithString:#"http://abcgroup.delivery-projects.com:81/api/index.php?keyword=docinsert"];
//self.request = [NSMutableURLRequest requestWithURL:url
// cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
self.request = [NSMutableURLRequest requestWithURL:url];
NSLog(#"Requst %#",request);
NSString *userid=[userDefaults valueForKey:#"UIDD"];
NSString *title=fileName;
NSString *docname=fileName;
NSString *size=[NSString stringWithFormat:#"%d",[data length]];
/*
NSString *post = [NSString stringWithFormat:#"userid=%#&title=%#&docname=%#&size=%#&content=%#",userid,title,docname,size,content];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
[self.request setHTTPMethod:#"POST"];
//NSString *POSTBoundary = [NSString stringWithFormat:#"0xKhTmLbOuNdArY"];
//[self.request addValue:[NSString stringWithFormat:#"multipart/form-data; boundary=%#\r\n", POSTBoundary] forHTTPHeaderField:#"Content-Type"];
[self.request setValue:[NSString stringWithFormat:#"%d", postData.length] forHTTPHeaderField:#"Content-Length"];
[self.request setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[self.request setHTTPBody:postData];
[NSURLConnection connectionWithRequest:self.request delegate:self];
*/
/////
NSMutableURLRequest *request11 = [[NSMutableURLRequest alloc] init] ;
[request11 setURL:url];
[request11 setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request11 addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
// Pdf File
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"content\"; filename=\"INSPECTION.pdf\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//[body appendData:[#"Content-Disposition: form-data; name=\"content\"\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:data]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userid\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",userid] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"title\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",#"TITLE_TEST1"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"docname\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",docname] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"size\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",size] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[request11 setHTTPBody:body];
[NSURLConnection connectionWithRequest:request11 delegate:self];
//[NSURLConnection sendSynchronousRequest:request11 returningResponse:nil error:nil];
/////
}
I used following function to upload images, audio and videos with slight modifications.
In this function urloptions is the query string that you want to send with file like userId and fileName.
Didn't get chance to upload PDF but hope this will help you.
-(NSString *)uploadFile:(NSString *)urloptions: (NSString *) ext :(NSData *)imageData{
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"%#&%#",APP_URL,urloptions]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:#"POST"];
NSString *boundary = [NSString stringWithString:#"---------------------------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:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"formFile\"; filename=\".%#\"\r\n",ext] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"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];
NSString *returnString = [[[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding] autorelease];
//NSLog(#"%#",returnString);
return returnString ;
//[returnString release];
}
While you can find a way to correctly post your data, it will be much easier and maintainable to use a wrapper around NSURLConnection such as STHTTPRequest https://github.com/nst/STHTTPRequest. Here is what your code will look like:
STHTTPRequest *r = [STHTTPRequest requestWithURLString:#"http://abcgroup.delivery-projects.com:81/api/index.php?keyword=docinsert"];
[r setFileToUpload:#"Inspection.pdf" parameterName:#"myFile"];
[r setPOSTDictionary:#{#"userid":#"", #"title":#"", #"docName":#""}]; // your parameters here
r.completionBlock = ^(NSDictionary *headers, NSString *body) {
// ...
};
r.errorBlock = ^(NSError *error) {
// ...
};
[r startAsynchronous];
To upload any type of file you can use ASIHttpRequest library that you can get from https://github.com/pokeb/asi-http-request.
To upload file use ASIFormDataRequest class of this library that makes your work easy.
first convert your pdf in binary
NSData theData = [NSData dataWithData:[GTMBase64 decodeString:theBinary]]; //first transfer it to NSData.
[m_oTestingWeb loadData:theData
MIMEType:#"application/pdf"
textEncodingName:#"UTF-8"
baseURL:nil]; //using the web view to show it back
then upload this data to server.
You have to create an API on the web server that the iPhone can contact in order to POST data to your web server. You can simply create an NSURLConnection in order to build your packet to post the data from the iPhone app.
Inside an NSURLConnection you can tell it to be a POST packet and then add data to the body of the request. Your image data should be converted to UTF8 and stored as a nvarchar or something along those lines in your database.
Understand, this is an overview of what you have to do, without knowledge of your internal workings of the web app I cannot give you specifics.
You can use the latest Library by AFNewtork:
With AFNetworking you can do it by:
NSURL *url = [NSURL URLWithString:#"my_base_url"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:#"yourfile.pdf"], 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:#"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData:imageData name:#"MainMedia" fileName:#"MainMedia" mimeType:#"image/jpeg"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(#"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[operation start];
}
Download AFNetworking library and add it to your project.
Two real issues that I can spot in "Tried 2"
It seems, you forgot the final delimiter - see Irfan DANISH post.
You need the binary of the pdf - not the UTF8.
Additionally, do not use a synchronous request - use the asynchronous style implementing the delegate methods.
And, you "should" set a Content-Length header for the pdf part.

JSON posting in iOS not working (.NET server)

Posting request to .NET server is not working.
NSDictionary *jsonDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSURL *postURL = [NSURL URLWithString: #"SOME URL"];
NSError *error=nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&error];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: postURL
cachePolicy: NSURLRequestUseProtocolCachePolicy
timeoutInterval: 60.0];
[request setHTTPMethod: #"POST"];
[request setValue: #"application/json" forHTTPHeaderField: #"Accept"];
[request setValue: #"application/json" forHTTPHeaderField: #"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d",[jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: jsonData];
NSLog(#"JSON summary: %#", [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding]);
The Output is:
{"CreatedBy":"","EmailAddress":"devanrajupericherl#gmail.com","Zipcode":"","FirstName":"devan","DeviceCategoryID:":"","State":"","CustomerTypeID:":"",..........} like this.....
But it Json object must be:
({CreatedBy:"",EmailAddress:"devanrajupericherl#gmail.com",Zipcode:"",FirstName:"devan",DeviceCategoryID::"",State:"",CustomerTypeID:"" })
I am using .Net server for Posting.
Request is not Posting to the Server. Anyone please help me.
NSString *urlString = #"Your Web Service URL";
NSString *parameterString = #"XYZ";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSMutableData *body = [NSMutableData data];
// parameter
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"parameter_key\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:parameterString dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// close form
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// now lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"returnString %#",returnString);

post image to server in iphone

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];
}
i used this code in my app and it works fine ...
//create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
//Set Params
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:#"POST"];
//Create boundary, it can be anything
NSString *boundary = #"------VohpleBoundary4QuqLuM1cE5lMwCy";
// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
// post body
NSMutableData *body = [NSMutableData data];
//Populate a dictionary with all the regular values you would like to send.
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
[parameters setValue:param1 forKey:#"param1-name"];
[parameters setValue:param2 forKey:#"param2-name"];
[parameters setValue:param3 forKey:#"param3-name"];
// add params (all params are strings)
for (NSString *param in parameters) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#\r\n", [parameters objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
NSString *FileParamConstant = #"imageParamName";
NSData *imageData = UIImageJPEGRepresentation(imageObject, 1);
//Assuming data is not nil we add this to the multipart form
if (imageData)
{
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type:image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
//Close off the request with the boundary
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the request
[request setHTTPBody:body];
// set URL
[request setURL:[NSURL URLWithString:baseUrl]];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
if ([httpResponse statusCode] == 200) {
NSLog(#"success");
}
}];
I used this code
// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
//Create boundary, it can be anything
NSString *boundary = #"------VohpleBoundary4QuqLuM1cE5lMwCy";
// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
// post body
NSMutableData *body = [NSMutableData data];
// add params (all params are strings)
for (NSString *param in _params) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
// add image data
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0);
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// set URL
[request setURL:requestURL];
it works like a charm.
Can you plz see the following code i hope it will be helpful to you.
Here is iOS code
-(void)createConnectionRequestToURL:(NSString *)urlStr withImage:(UIImage*)image withImageName:(NSString*)imageName
{
NSData *imageData = UIImageJPEGRepresentation(image, 90);
NSString *urlString = urlStr;
// setting up the request object now
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = [[NSString alloc]init];
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=\"file\"; filename=\"test.png\"rn" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Type: application/%#.jpg\r\n\r\n",imageName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
//Using Synchronous Request. You can also use asynchronous connection and get update in delegates
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"--------%#",returnString);
}
Find here serverside (PHP) coding for image Upload with random name. also it will give the image link as response.
//Create a folder named images in your server where you want to upload the image.
// And Create a PHP file and use below code .
<?php
$uploaddir = 'images/';
$ran = rand () ;
$file = basename($_FILES['userfile']['name']);
$uploadfile = $uploaddir .$ran.$file;
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "www.host.com/.../images/{$uploadfile}";
}
?>
(OR)
<?php
$request_body = #file_get_contents('php://input');
foreach (getallheaders() as $name => $value)
{
if ($FileName=="FileName")
{
$header=$value;
break;
}
}
$uploadedDir = "directory/";
#mkdir($uploadedDir);
file_put_contents($uploadedDir."/".$FileName.".txt",
$request_body.PHP_EOL, FILE_APPEND);
header('X-PHP-Response-Code: 202', true, 202);
?>
I used this code and it works fine.
If you want more accuracy and speed you can compress the image then upload, but compression is an optional part.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
// RP: Empaquetando datos
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:[NSString stringWithFormat:#"%#",loginoneid] forKey:#"user_id"];
[_params setObject:[NSString stringWithFormat:#"%#",_strpostid] forKey:#"post_id"];
// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
NSString *BoundaryConstant = #"V2ymHFg03ehbqgZCaKO6jy";
// string constant for the post parameter 'file'
NSString *FileParamConstant = #"files[]";
//RP: Configurando la dirección
NSURL *requestURL = [[NSURL alloc] initWithString:#"http://www.hugosys.in/www.nett-torg.no/api/rpcs/uploadfiles/"];
// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", BoundaryConstant];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
// post body
NSMutableData *body = [NSMutableData data];
// add params (all params are strings)
for (NSString *param in _params) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
if (imageData) {
printf("appending image data\n");
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\'%#\'; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// set the content-length
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// set URL
[request setURL:requestURL];
NSURLResponse *response = nil;
NSError *err = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
dispatch_async(dispatch_get_main_queue(), ^{
NSString *str = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
I have made block method which you can use all class just create NSObject and for Example you have created
AFClass.h
AFClass.m
So Write this line in your class header file (This is class method so you can simply call by class name as well)
+(NSURLSessionDataTask *)postImageRequestWithURL:(NSString *)URL andParam:(NSDictionary *)param withImages:(NSDictionary *)imageArray response:(void (^)(NSDictionary *posts, NSError *error))block;
And write this code in AFClass.m class
+(NSURLSessionDataTask *)postImageRequestWithURL:(NSString *)URL andParam:(NSDictionary *)param withImages:(NSDictionary *)imageArray response:(void (^)(NSDictionary *posts, NSError *error))block
{
//show Progress hud
[SVProgressHUD showWithStatus:#"Loading..."];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:URL parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
for (NSString *strKey in [imageArray allKeys])
{
if ([[imageArray valueForKey:strKey] isKindOfClass:[NSData class]])
{
NSString *strFilename = [NSString stringWithFormat:#"%u.jpg",arc4random()];
[formData appendPartWithFileData:[imageArray valueForKey:strKey] name:strKey fileName:strFilename mimeType:#"image/jpeg"];
}
}
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress)
{
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error)
{
if (error)
{
[SVProgressHUD dismiss];
if (block)
{
block(nil, error);
}
}
else
{
[SVProgressHUD dismiss];
if (block)
{
block(responseObject, nil);
}
}
}];
[uploadTask resume];
return uploadTask;
}
Now I call this class method Here i am giving example
// Set Your URL Here
NSString *strURL = #“Write your URL Here”
// Set Your Post Data Here
NSMutableDictionary *postData = [NSMutableDictionary dictionaryWithDictionary:#{#"user_id”:#“54”,#“first_name”:#“Jignesh”}];
// Here you can send multiple image convert your UIimage to NSData
NSDictionary *profileData = #{#"uploaded_file":UIImageJPEGRepresentation(profilePic,1.0),#"uploaded_file1”:UIImageJPEGRepresentation(profilePic1,1.0)};
Now Call Your class Method for Upload Images
[AFClass postImageRequestWithURL:strURL andParam:postData withImages:profileData response:^(NSDictionary *response, NSError *error)
{
// Here is your Response
}];

Object reference not set to an instance of an object In XML

I am new to iPhone and using XML in my application where i need to send one image to the server's one specific folder. For the same i am using the code :
NSString *filename = #"Image";
NSData *imageData = UIImageJPEGRepresentation([imageView image], 90);
NSString *urlString = [NSString stringWithFormat:#"http://111.111.11.1/webservices.asmx/PutImage"];
//url is : http://111.111.11.1/webservices.asmx/PutImage?ImgIn=image.jpg
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = [NSString stringWithString:#"--------1473780983"];
NSString *contentType = [NSString stringWithFormat:#"application/x-www-form-urlencoded;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:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"images\"; filename=\"%#.jpg\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"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];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"\n\n\nreturnString : %#",returnString);
I am getting message like : "Object reference not set to an instance of an object" in return string. Can anybody guide me with some solution?
Ok... Try my code that i m using....
//imageview is a UIImageView
NSData *imageData = UIImageJPEGRepresentation(imageview.image, 100);
// setting up the URL to post to
NSString *urlString = #"http://example.com/upload";
// setting up the request object now
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
/*
add some header info now
we always need a boundary when we post a file
also we need to set the content type
You might want to generate a random boundary.. this is just the same
as my output from wireshark on a valid html post
*/
NSString *boundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
/*
now lets create the body of the post
*/
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"userfile\"; filename=\".jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"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]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// now lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
self.returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
To upload data from your iPhone to your server:
- (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];
}