Send post variables along with Image to php server in POST method - ios

I am trying upload an image along with some form fields. I am able to upload image to server using the following link as a reference.
File Upload to HTTP server in iphone programming
But if i try to send some form fields along with the image i am error response. Here is the code i am using
-(void)saveData{
NSString *urlString = #"Sample url";
NSString *filename = #"filename";
NSMutableURLRequest *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 *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[self generateDataFromText:FORM DATA IN JSON fieldName:#"add_product"]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"files\"; filename=\"%#.jpg\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:fileData]];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];
[request setValue:APIKEY forHTTPHeaderField:#"X-API-KEY"];
NSURLResponse *urlResp;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResp error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSHTTPURLResponse *resp = (NSHTTPURLResponse *) urlResp;
NSLog(#"status code: %ld, response string: %#",(long)[resp statusCode],returnString);
}
-(NSMutableData *)generateDataFromText:(NSString *)dataText fieldName:(NSString *)fieldName
{
NSString *post = [NSString stringWithFormat:#"--AaB03x\r\nContent-Disposition: form-data; name=\"%#\"\r\n\r\n", fieldName];
// Get the post header int ASCII format:
NSData *postHeaderData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// Generate the mutable data variable:
NSMutableData *postData = [[NSMutableData alloc] initWithLength:[postHeaderData length]];
[postData setData:postHeaderData];
NSData *uploadData = [dataText dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// Add the text:
[postData appendData: uploadData];
// Add the closing boundry:
[postData appendData: [#"\r\n" dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];
// Return the post data:
return postData;
}
So some one please help me to send form data along with am image to PHP server using POST method. Thanks in advance.

Every Field should be in its own boundary #"\r\n--%#\r\n". So make the following changes to make the code work.
Remove the line:
[postbody appendData:[self generateDataFromText:FORM DATA IN JSON fieldName:#"add_product"]];
And after the line
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
put the following code:
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; add_product=\"%#\"\r\n\r\n",key] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[self generateDataFromText:FORM DATA IN JSON] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithString:#"\r\n--%#\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
for every field, you need to add these 4 lines.
You should think to use AFNetworking instead. Its easy to work.
Getting it to work with AFNetworking is very easy. Add AFNetworking into your project through Cocoapods, here are the instructions:
https://github.com/AFNetworking/AFNetworking
Once AFNetworking is setup, use the following code:
NSString *apiName = URL;
UIImage *yourImage;
NSData *imgData = UIImageJPEGRepresentation(yourImage,1.0);
imgData = [imgData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];];
NSData *otherFields = [self generateDataFromText:FORM DATA IN JSON];
NSDictionary * params = [[NSDictionary alloc] initWithObjectsAndKeys:imgData, #"imgFieldName",otherFields,#"add_product",nil];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:apiName parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
//posted successfully
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//failed
}];
This is very simple Post method with image encoded in Base64. You can add as many fields into params dictionary as needed.

Related

POST multipart/form-data with Objective-C for image and other parameter

I've looked into a good number of articles on how to do a multipart/form-data POST on iOS, but none really explain what to do if there were normal parameters as well as the file upload.
I have used the multipart/form-data POST on iOS & I had written the following code and it is uploading data but not image data
- (void)postWithImage:(NSDictionary *)dictionary
{
NSString *urlString = [NSString stringWithFormat:#"YourHostString"];
NSURL *url = [NSURL URLWithString:urlString];
NSString *boundary = #"----1010101010";
// define content type and add Body Boundry
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSEnumerator *enumerator = [dictionary keyEnumerator];
NSString *key;
NSString *value;
NSString *content_disposition;
while ((key = (NSString *)[enumerator nextObject])) {
if ([key isEqualToString:#"file"]) {
value = (NSString *)[dictionary objectForKey:key];
NSData *postData = UIImageJPEGRepresentation([UIImage imageNamed:value], 1.0);
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\";\r\nfilename=\"screen.png\"\r\n\r\n",value] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:postData];
} else {
value = (NSString *)[dictionary objectForKey:key];
content_disposition = [NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", key];
[body appendData:[content_disposition dataUsingEncoding:NSUTF8StringEncoding]];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:value options:NSJSONWritingPrettyPrinted error:&error];
[body appendData:jsonData];
//[body appendData:[value dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
}
//Close the request body with Boundry
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[request addValue:[NSString stringWithFormat:#"%d", body.length] forHTTPHeaderField: #"Content-Length"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#", returnString);
}
Can anyone please help me to get why image data is not uploading
I think you should append #"content-Type" before you append real data, like this:
[body appendData:[#"Content-Type: image/png\r\n\r\n"
dataUsingEncoding:NSUTF8StringEncoding]];

Upload multipart image with NSData in JSON (HTTP body)

I'm trying to upload a multipart image to server where image is converted to NSData and this NSdata is sent a parameter in HTTP body in a JSON string. Unfortunately the app crashes with this message:
**'NSInvalidArgumentException', reason: 'Invalid type in JSON write (NSConcreteMutableData)'**
I understand that the problem is with JSON. The sample code:
-(void) uploadmultipartimage {
NSString * urlimageupload = [NSString stringWithFormat:#"%#api/mobile_profiles/avatar_upload",URLPrefixCertintell];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlimageupload]];
NSData *imageData = UIImageJPEGRepresentation(_profileimage, 1.0);
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:#"PUT"];
NSString *boundary = #"unique-consistent-string";
// 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)
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=%#\r\n\r\n", #"imageCaption"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#\r\n", #"Some Caption"] dataUsingEncoding:NSUTF8StringEncoding]];
// add image data
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=%#; filename=imageName.jpg\r\n", #"imageFormKey"] 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", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSDictionary *jsonString = #{#"user":#{#"user_token":[[NSUserDefaults standardUserDefaults] stringForKey:#"user_token"]},#"api_key":APIKey,#"profile":body};
//***Code Crashes here**//
NSData *postData = [NSJSONSerialization dataWithJSONObject:jsonString options:0 error:nil];
//
// setting the body of the post to the reqeust
[request setHTTPBody:postData];
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if(data.length > 0) {
//success
}
}];
}
You need to convert your data to NSString:
NSString *g=[[NSUserDefaults standardUserDefaults] stringForKey:#"user_token"];
if (!g)
g=#"Default Token";
NSString *base64Body = [body base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
NSDictionary *jsonString = #{#"user":#{#"user_token":g},#"api_key":APIKey,#"profile":base64Body};
Then you can always argue about the possibility of nil when reading the "user_token".
Take care,
/Anders.

Upload image to web service in ios

I tried AFNetworking's "Create an upload task" and this to upload image in .net server, but couldn't. This is what I tried.
- (void)uploadJPEGImage:(NSString*)requestURL image:(UIImage*)image
{
NSURL *url = [[NSURL alloc] initWithString:requestURL];
NSMutableURLRequest *urequest = [NSMutableURLRequest requestWithURL:url];
[urequest setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[urequest setHTTPShouldHandleCookies:NO];
[urequest setTimeoutInterval:60];
[urequest setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[urequest setValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
// add image data
NSData *imageData = UIImageJPEGRepresentation(qrCodeImage.image, 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", pictureName] 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", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[urequest setHTTPBody:body];
NSLog(#"Check response if image was uploaded after this log");
//return and test
NSData *returnData = [NSURLConnection sendSynchronousRequest:urequest returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#", returnString);
}
Since AFNetworking code gives, me this run time error despite adding
self.acceptableContentTypes = [[NSSet alloc] initWithObjects:#"application/xml", #"text/xml", #"text/html", nil];
Thanks.
Your code was missing the __VIEWSTATE content par. I've added in code to extract the URL of the uploaded image at the end:
- (void)uploadJPEGImage:(NSString*)requestURL image:(UIImage*)image
{
NSURL *url = [[NSURL alloc] initWithString:requestURL];
NSMutableURLRequest *urequest = [NSMutableURLRequest requestWithURL:url];
[urequest setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[urequest setHTTPShouldHandleCookies:NO];
[urequest setTimeoutInterval:60];
[urequest setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[urequest setValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
// Add __VIEWSTATE
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"__VIEWSTATE\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"/wEPDwUKLTQwMjY2MDA0M2RkXtxyHItfb0ALigfUBOEHb/mYssynfUoTDJNZt/K8pDs=" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// add image data
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"FileUpload1\"; filename=\"image.jpg\"\r\n" 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", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[urequest setHTTPBody:body];
NSLog(#"Check response if image was uploaded after this log");
//return and test
NSHTTPURLResponse *response = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:urequest returningResponse:&response error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#", returnString);
// Extract the imageurl
NSArray *parts = [returnString componentsSeparatedByString:#"\r\n"];
if (parts.count > 0) {
NSError *error = NULL;
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[parts[0] dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&error];
NSLog(#"%#", result[#"imageurl"]); // Will either be nil or a URL string
}
}
1.I think you miss the hidden input in upload page:
2.Using the code below, i can upload successfully and get the right response string:
UIImage *image = [UIImage imageNamed:#"a.jpg"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer new];
// add hidden parameter here
NSDictionary * parameters = #{#"__VIEWSTATE":#"/wEPDwUKLTQwMjY2MDA0M2RkXtxyHItfb0ALigfUBOEHb/mYssynfUoTDJNZt/K8pDs="};
[manager POST:#"http://cnapi.iconnectgroup.com/upload/fileuploadnew.aspx" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
// add image date here
[formData appendPartWithFileData:UIImageJPEGRepresentation(image, 0.5) name:#"FileUpload1" fileName:#"avatar.jpg" mimeType:#"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSData * data = (NSData *)responseObject;
NSLog(#"Success,Response string: %#", [NSString stringWithCString:[data bytes] encoding:NSISOLatin1StringEncoding]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

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 :)

Resources