Sending Image to server from IOS - ios

In my IOS app I want to send an image to the server along with Image name using HTTP request.
I am a programmer with embedded Background so not aware with HTTP calls, and quite new to iPhone development also.
How can I accomplish this, any sample code or tutorials will be appreciated.

The better approach is to first compress your image using Image Compress Library Here and then upload it using and Networking library Liek AF Networking or you can also send it using NSUrlConnection. AFNetworking is easy to use. You can visit this page to see how to import this into your project then. Write these lines of codes.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSURL *filePath = [NSURL fileURLWithPath:#"file://path/to/image.png"];
[manager POST:#"http://samwize.com/api/poo/"
parameters:#{#"color": #"green"}
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:filePath name:#"image" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

The easiest way for you from my point of view would be to use AFNetworking.
It'll send the image to a php page, then on the server, you build and save the image with the data sent.
Here's a basic tutorial, but lot of others on internet.

For this you can do something like this by using ASIHTTPRequest
NSURL *strUrl = [NSURL URLWithString:[NSString stringWithFormat:#"%#?action=youraction",serverUrl]];
ASIFormDataRequest *request;
request = [[[ASIFormDataRequest alloc] initWithURL:strUrl] autorelease];
[request setRequestMethod:#"POST"];
[request setTimeOutSeconds:120];
NSString *imagePAth = userImagePath;
NSArray *imageName = [userImagePath componentsSeparatedByString:#"/"];
if( userImagePath)
{
[request setFile:imagePAth withFileName:[imageName lastObject] andContentType:#"image/jpeg" forKey:#"profileImage"];
}
[request setUseCookiePersistence:NO];
[request setUseSessionPersistence:NO];
[request setDelegate:self];
[request setDidFinishSelector:#selector(requestFinished:)];
[request setDidFailSelector:#selector(requestFailed:)];
[request startAsynchronous];
- (void)requestFinished:(ASIHTTPRequest *)request
{
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
}

Use NSURLConnection, make sure that you convert images to NSData
user_id and key there are parameters.
NSURL *URL = [NSURL URLWithString:constFileUploadURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"0xLhTaLbOkNdArZ";
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", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"user_id\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *userid = [NSString stringWithFormat:#"%li",userID];
[body appendData:[userid dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"key\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[constBackendKey dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
for (NSData *data in arrayWithFiles)
{
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"files%ld\"; filename=\"image%ld.jpg\"\r\n",[arrayWithFiles indexOfObject:data],[arrayWithFiles indexOfObject:data]] 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 stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
_connection = [NSURLConnection connectionWithRequest:request delegate:self];

Related

How to post image on server with dictionary iOS?

I have a dictionary (dict) of some keys/values and an image. Now I want to upload image to server with dictionary. I have already try this but not getting any success. Here is my sample code--
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSMutableData *body = [NSMutableData data];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSData *imageData = UIImageJPEGRepresentation(image,0.5);//or you can use png representation- UIImagePNGRepresentation(image);
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"thumbnail\"; filename=\"image.png\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// parameter all_data
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"all_data\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",dict] 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 request
[request setHTTPBody:body];
NSError *error=nil;
NSHTTPURLResponse *response=nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
I need help where is I'm going wrong.. Thanks in advance
Try out the below code:
-(void)uploadImage:(NSString *)api :(NSDictionary *)params : (UIImage *)image {
NSURL *myURL = [NSURL URLWithString:api];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:myURL];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#; charset=UTF-8", boundary];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
NSMutableData *theBodyData = [NSMutableData data];
for (int i=0; i<[[params allKeys] count]; i++)
{
[theBodyData appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *value=#"";
value=[params objectForKey:[[params allKeys] objectAtIndex:i]];
NSString * value1=[NSString stringWithFormat:#"Content-Disposition: form-data; name=%#\r\n\r\n%#\r\n",[[params allKeys] objectAtIndex:i],value];
[theBodyData appendData:[value1 dataUsingEncoding:NSUTF8StringEncoding]];
}
[theBodyData appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[theBodyData appendData:[#"Content-Disposition: form-data; name=\"my_file1\"; filename=\"image1.jpeg\"\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
[theBodyData appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
NSData *myData = UIImageJPEGRepresentation(image,0.5);
[theBodyData appendData:[NSData dataWithData:myData]];
[theBodyData appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:theBodyData];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", (int)[theBodyData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: theBodyData];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSURLSessionDataTask * dataTask =[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Server Raw Response : %#",responseString);
}
}];
[dataTask resume];
}
Your code looks fine but I think you have to convert your dictionary into json string. Just Replace this line-
[body appendData:[[NSString stringWithFormat:#"%#",dict] dataUsingEncoding:NSUTF8StringEncoding]];
with
NSString *jsonStr = [[NSString alloc]initWithData:[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
[body appendData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
may be this will help you.

How to send form-data and x-www-form-urlencoded both in same POST request in ios?

I have a problem. I am making POST request to server. In which I am uploading an Image with user_id of User.I need to send user_id in x-www-form-urlencoded and Image in from-data. I tried many ways but every time user_id is undefined in server. How can I send both in same request.
Here is my CODE:
NSString *urlString = [[NSString alloc]initWithString:[NSString stringWithFormat:#"MY URL TO UPLOAD IMAGE "]];
urlString=[urlString stringByAddingPercentEscapesUsingEncoding:
NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:100];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"------V2ymHFg03ehbqgZCaKO6jy";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
[request addValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSDictionary *params = #{#"user_id":#"213"};
NSMutableData *body = [NSMutableData data];
for (NSString *param in params) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: x-www-form-urlencoded; 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(image, .3);
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"my-file\"; filename=\"%#.jpg\"\r\n",#"213"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: image/jpg\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];
NSURLResponse *urlResponse;
NSError *error;
NSData * data=[NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
Output: data = nil
In order to send your data through POST
[request setHTTPMethod:#"POST"];
NSString *myString = [NSString stringWithFormat:#"value1=test3&value2=test"];
[request setHTTPBody:[myString dataUsingEncoding:NSUTF8StringEncoding]];

Send parameter with image by POST method?

I want to send my image with parameter (username, password..etc) ?? following is my code:
-(void) senRequestForPostAnswerWithImage:(NSString *)imageName andAnswer:(NSString *)answer andQuestionID:(NSString *)questionID
{
NSUserDefaults *loginData = [NSUserDefaults standardUserDefaults];
NSString *username = [loginData objectForKey:#"username"] ;
NSString *password = [loginData objectForKey:#"password"];
NSString *postString = [NSString stringWithFormat:#"&username=%#&password=%#&image=%#&answer=%#&question_id=%#", username, password, imageName, answer, questionID];
NSString *urlString = #"http://myAPIName/MethodName";
NSURL *myURL = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *detailRequestToServer =[NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
[detailRequestToServer setHTTPMethod:#"POST"];
[detailRequestToServer setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
const char *utfString = [postString UTF8String];
NSString *utfStringLenString = [NSString stringWithFormat:#"%zu", strlen(utfString)];
[detailRequestToServer setHTTPBody:[NSData dataWithBytes: utfString length:strlen(utfString)]];
[detailRequestToServer setValue:utfStringLenString forHTTPHeaderField:#"Content-Length"];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:detailRequestToServer delegate:self];
if (theConnection)
{
self.responseData = [[NSMutableData alloc] init];
[GeneralClass startHUDWithLabel:#"Loading…"];
}
else
NSLog(#"Connection Failed!");
}
I know there are many question on this site but I don't know where and what I need to change in my existing code ??
So, please suggest me what I need to change in my existing code for add functionality of send image ??
NOTE: without image this above code is working well for me.
My suggestion would be to use AFNetworking. It will simplify the process for your considerably and save you a lot of time. It is widely used framework by developers.
https://github.com/AFNetworking/AFNetworking
You can easily send image with parameters using just few lines (POST-multipart request):
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"foo": #"bar"};
NSURL *filePath = [NSURL fileURLWithPath:#"file://path/to/image.png"];
[manager POST:#"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:filePath name:#"image" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
As far as I know, you can't directly send it as UIImage. You need to convert it to NSData, which the gets decoded on the server side.
Another alternative, is to upload the image somewhere, which can be accessed via a URL. (But this is usually done on the server side and the URL is given back as response).
There's a post here about converting UIImage to NSData.
using this you can pass parameters as well as with image data.
NSString *urlString = [NSString stringWithFormat:#"http://myAPIName/MethodName/test.php&username=%#&password=%#&image=%#&answer=%#&question_id=%#", username, password, imageName, answer, questionID];
NSLog(#"MyURL: %#",urlString);
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
request = [[NSMutableURLRequest alloc] init];
[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]];
NSString *str=[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"SourceImage\"; filename=\"Image_%#\"\r\n",[imagePath lastPathComponent]];
[body appendData:[[NSString stringWithString:str] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithContentsOfFile:imagePath]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
If you want to send parameter with image by post method then use following code. Its working very well for me..
I tried to change my code as per your requirement, follow it.
You need to create NSMutableDictionary and add your parameter on it and also append this dictionary to NSMutableData as JSON formate. (You need to add NSMutableData Library to your project)
-(void) senRequestForPostAnswerWithImage:(NSString *)imageName andAnswer:(NSString *)answer andQuestionID:(NSString *)questionID
{
NSUserDefaults *loginData = [NSUserDefaults standardUserDefaults];
NSString *username = [loginData objectForKey:#"username"] ;
NSString *password = [loginData objectForKey:#"password"];
// create NSMutableDictionary for store parameter
NSMutableDictionary *dicOfData = [[NSMutableDictionary alloc] init];
[dicOfData setObject:username forKey:#"username"];
[dicOfData setObject:password forKey:#"password"];
[dicOfData setObject:imageName forKey:#"imageName"];
[dicOfData setObject:answer forKey:#"answer"];
[dicOfData setObject:questionID forKey:#"questionID"];
NSString *url = #"http://myAPIName/MethodName";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
/// create NSMutableData to store data of dictionary
NSMutableData *body = [NSMutableData data];
NSString *boundary = #"--iOS Boundary Line--";
[request addValue:[NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary] forHTTPHeaderField: #"Content-Type"];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *imgPath = [documentsDir stringByAppendingPathComponent:imageName];
if([imageName length] > 0)
{
if([[NSFileManager defaultManager] fileExistsAtPath:imgPath])
{
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"photo\"; filename=\"%#\"\r\n", imageName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithContentsOfFile:imgPath]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
}
}
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"requestData\"\r\n\r\n%#", [dicOfData JSONRepresentation] ] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[request addValue:[NSString stringWithFormat:#"%d", [body length]] forHTTPHeaderField:#"Content-Length"];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection)
{
self.responseData = [[NSMutableData alloc] init];
}
else
NSLog(#"Connection Failed!");
}
At your server (PHP) side.. you get image (object and name if you added) with other parameter in dictionary formate.
Refer this code - It works perfect for me -
NSString *userID = mainDelegate.loginUserPin;
UIImage *imag = self.addImage;
NSString *urlString = mainDelegate.I2K2_Webservice_Url;
NSData *imageData = UIImageJPEGRepresentation(imag, 90);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
[request setTimeoutInterval:6*60000];
NSString *boundary = #"*****";
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]];
//Title
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"title\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#~%#",userID,txtName.text] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//Description
[body appendData:[#"Content-Disposition: form-data; name=\"description\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *imgNameString = [NSString stringWithFormat:#"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"%#~%#\"\r\n",userID,txtName.text];
NSLog(#"imgNameString : %#",imgNameString);
[body appendData:[[NSString stringWithString:imgNameString] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"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);
You cant send UIImage by specifying it's name to web server. You should include it in the HTTP body as NSData .I used ASIHTTPRequest, it was simple and perfect. Use ASIHTTPRequest. A sample code is given below
NSData *imgData = UIImageJPEGRepresentation(IMAGE_HERE, 0.9);
formReq = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlString]];
formReq.delegate = self;
[formReq setPostValue:VALUE1 forKey:KEY1];
[formReq setPostValue:VALUE2 forKey:KEY2];
if (imgData) {
[formReq setData:imgData withFileName:#"SAMPLE.jpg" andContentType:#"image/jpeg" forKey:IMAGE_KEY];
}
[formReq startSynchronous];

send image to twitter via oauth

I am successfully able to login on twitter with oauth. Now I need to post image with status. For that I have implemented following..
-(void)shareontw{
NSString *postUrl =#"https://api.twitter.com/1.1/statuses/update_with_media.json";
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:postUrl]];
[req setValue:[oAuth oAuthHeaderForMethod:#"POST" andUrl:postUrl andParams:nil] forHTTPHeaderField:#"Authorization"];
[req setHTTPMethod:#"POST"];
NSString *boundary = #"0xKhTmLbOuNdArY---This_Is_ThE_BoUnDaRyy---pqo";
NSString *headerBoundary = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",
boundary];
[req addValue:headerBoundary forHTTPHeaderField:#"Content-Type"];
NSMutableData *myRequestData = [NSMutableData data];
NSData *imageData = UIImageJPEGRepresentation(globalimage, 0.8);
[myRequestData appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData appendData:[#"Content-Disposition: form-data; name=\"media\"; filename=\"dummy.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData appendData:[#"Content-Type: image/jpeg\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData appendData:[#"Content-Transfer-Encoding: binary\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// add it to body
[myRequestData appendData:imageData];
[myRequestData appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData appendData:[#"Content-Disposition: form-data; name=\"message\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData appendData:[#"Success\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[req setHTTPBody:myRequestData];
NSHTTPURLResponse *response;
NSError *error = nil;
NSString *responseString = [[[NSString alloc] initWithData:[NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error] encoding:NSUTF8StringEncoding] autorelease];
if (error) {
NSLog(#"Error from NSURLConnection: %#", error);
}
NSLog(#"Got HTTP status code from Twitter after posting profile image: %d", [response statusCode]);
NSLog(#"Response string: %#", responseString);}
But it giving me error: Response string: {"errors":[{"message":"Bad Authentication data","code":215}]}
I am unable to find the issue that what I am doing wrong here. Please if some has idea then help me out.
Thanks in advance.
thanks your above code is working fine and save a lot of time for me.i just change one line of code
this line NSData *imageData = UIImageJPEGRepresentation(globalimage, 0.8);
replace with
NSData *imageData = UIImageJPEGRepresentation(_imgView.image, 0.8);
and it's working :)

Error 400 while uploading image from ios

I am very much new to ios.I have to upload an image to rest server from ios application. I have referred stackoverflow. But everytime the response is 400 which is bad request from client side. I am taking image from device document directory.Could some one post the exact code for image upload.Please refer the code I am using. I am not sure what to use as file name since I am downloading image from documents directory.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"POST"];
[request setURL:[NSURL URLWithString:#"urltoupload"]];
NSString *stringBoundary = #"----1010101010";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",stringBoundary];
[request setValue:contentType forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition:attachment; name=\"userfile\"; filename=\"image.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:pngImageData];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *str = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"return Data ---- %#", str);
Try this:
// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
// 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", 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", [_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 URL
[request setURL:requestURL];
Hope it Helps!!
First convert UIImage to NSData as follows
UIImage *image = [UIImage imageNamed:#"example.png"];
NSData *data = UIImagePNGRepresentation(image);
or
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0);
Then form your request string
NSURL *url = [NSURL URLWithString:serverURL];
//Time out interval need to be tuned
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: [requestString dataUsingEncoding:NSUTF8StringEncoding]];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
if (!data)
{
NSLog(#"Error downloading data: %#", error);
return;
}
NSError *error1;
NSDictionary *theDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error1];
DLog(#"Data received :%#", theDict);
}];

Resources