Multipart ImageUpload with Param data in IOS - ios

I am trying to upload image with some text data. But When i try it for image upload only. it works! But for param, I am getting result=null. so data is sending null. here is my code.
-(void)uploadImage : (UIImage *)image : (NSString *)url : (NSString *)param
{
NSLog(#"URL : %#", url);
NSLog(#"param : %#", param);
NSData *myData=UIImagePNGRepresentation(image);
NSMutableURLRequest *request;
NSString *urlString = url;
NSString *filename = #"image";
request= [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSDictionary *temp = #{#"result" : #"rob"
};
//opening boundary
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:[[NSString stringWithFormat:#"--%#--", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"file\"; filename=\"%#.png\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:myData]];
//params
[postbody appendData:[ [temp description] dataUsingEncoding:NSUTF8StringEncoding]];
//closing boundary
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
// conn.delegate = self;
[conn start];
}
may any expert help me what i am missing?

You could use a library like AFNetworking for all your requests. It's very easy and makes your code more readable. Here is a way to create a multipart file upload with parameters (https://github.com/AFNetworking/AFNetworking#creating-an-upload-task-for-a-multi-part-request-with-progress)
NSDictionary *params = #{
#"result" : #"rob"
}
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:#"http://example.com/upload" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:#"file://path/to/image.jpg"] name:#"file" fileName:#"filename.jpg" mimeType:#"image/jpeg" error:nil];
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSProgress *progress = nil;
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"%# %#", response, responseObject);
}
}];
[uploadTask resume];

Related

iOS: How to call an post method, which contains some parameters and file(attachment)? [duplicate]

So this HTML code submits the data in the correct format for me.
<form action="https://www.example.com/register.php" method="post" enctype="multipart/form-data">
Name: <input type="text" name="userName"><BR />
Email: <input type="text" name="userEmail"><BR />
Password: <input type="text" name="userPassword"><BR />
Avatar: <input type="file" name="avatar"><BR />
<input type="submit">
</form>
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.
Could you please help me with the code to POST this in Obj-C?
Thanks!
The process is as follows:
Create dictionary with the userName, userEmail, and userPassword parameters.
NSDictionary *params = #{#"userName" : #"rob",
#"userEmail" : #"rob#email.com",
#"userPassword" : #"password"};
Determine the path for the image:
NSString *path = [[NSBundle mainBundle] pathForResource:#"avatar" ofType:#"png"];
Create the request:
NSString *boundary = [self generateBoundaryString];
// configure the request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
// set content type
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
// create body
NSData *httpBody = [self createBodyWithBoundary:boundary parameters:params paths:#[path] fieldName:fieldName];
This is the method used above to build the body of the request:
- (NSData *)createBodyWithBoundary:(NSString *)boundary
parameters:(NSDictionary *)parameters
paths:(NSArray *)paths
fieldName:(NSString *)fieldName {
NSMutableData *httpBody = [NSMutableData data];
// add params (all params are strings)
[parameters enumerateKeysAndObjectsUsingBlock:^(NSString *parameterKey, NSString *parameterValue, BOOL *stop) {
[httpBody appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[httpBody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", parameterKey] dataUsingEncoding:NSUTF8StringEncoding]];
[httpBody appendData:[[NSString stringWithFormat:#"%#\r\n", parameterValue] dataUsingEncoding:NSUTF8StringEncoding]];
}];
// add image data
for (NSString *path in paths) {
NSString *filename = [path lastPathComponent];
NSData *data = [NSData dataWithContentsOfFile:path];
NSString *mimetype = [self mimeTypeForPath:path];
[httpBody appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[httpBody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"%#\"\r\n", fieldName, filename] dataUsingEncoding:NSUTF8StringEncoding]];
[httpBody appendData:[[NSString stringWithFormat:#"Content-Type: %#\r\n\r\n", mimetype] dataUsingEncoding:NSUTF8StringEncoding]];
[httpBody appendData:data];
[httpBody appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}
[httpBody appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
return httpBody;
}
The above uses the following utility methods:
#import MobileCoreServices; // only needed in iOS
- (NSString *)mimeTypeForPath:(NSString *)path {
// get a mime type for an extension using MobileCoreServices.framework
CFStringRef extension = (__bridge CFStringRef)[path pathExtension];
CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, extension, NULL);
assert(UTI != NULL);
NSString *mimetype = CFBridgingRelease(UTTypeCopyPreferredTagWithClass(UTI, kUTTagClassMIMEType));
assert(mimetype != NULL);
CFRelease(UTI);
return mimetype;
}
- (NSString *)generateBoundaryString {
return [NSString stringWithFormat:#"Boundary-%#", [[NSUUID UUID] UUIDString]];
}
Then submit the request. There are many, many options here.
For example, if using NSURLSession, you could create NSURLSessionUploadTask:
NSURLSession *session = [NSURLSession sharedSession]; // use sharedSession or create your own
NSURLSessionTask *task = [session uploadTaskWithRequest:request fromData:httpBody completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"error = %#", error);
return;
}
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"result = %#", result);
}];
[task resume];
Or you could create a NSURLSessionDataTask:
request.HTTPBody = httpBody;
NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"error = %#", error);
return;
}
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"result = %#", result);
}];
[task resume];
The above assumes that the server is just returning text response. It's better if the server returned JSON, in which case you'd use NSJSONSerialization rather than NSString method initWithData.
Likewise, I'm using the completion block renditions of NSURLSession above, but feel free to use the richer delegate-based renditions, too. But that seems beyond the scope of this question, so I'll leave that to you.
But hopefully this illustrates the idea.
I'd be remiss if I didn't point that, much easier than the above, you can use AFNetworking, repeating steps 1 and 2 above, but then just calling:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer]; // only needed if the server is not returning JSON; if web service returns JSON, remove this line
NSURLSessionTask *task = [manager POST:urlString parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSError *error;
if (![formData appendPartWithFileURL:[NSURL fileURLWithPath:path] name:#"avatar" fileName:[path lastPathComponent] mimeType:#"image/png" error:&error]) {
NSLog(#"error appending part: %#", error);
}
} progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"responseObject = %#", responseObject);
} failure:^(NSURLSessionTask *task, NSError *error) {
NSLog(#"error = %#", error);
}];
if (!task) {
NSLog(#"Creation of task failed.");
}
POST multiple images using multipart or form-data with Objective-C
-(void)multipleimageandstring
{
NSString *urlString=#"URL NAME";
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"];
// file
float low_bound = 0;
float high_bound =5000;
float rndValue = (((float)arc4random()/0x100000000)*(high_bound-low_bound)+low_bound);//image1
int intRndValue = (int)(rndValue + 0.5);
NSString *str_image1 = [#(intRndValue) stringValue];
UIImage *chosenImage1=[UIImage imageNamed:#"Purchase_GUI_curves-12 copy.png"];
NSData *imageData = UIImageJPEGRepresentation(chosenImage1, 90);
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"files\"; filename=\"%#.png\"\r\n",str_image1] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"name\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Nilesh" 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=\"apipassword\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:app.password] 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=\"adminId\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:app.adminId] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// close form
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// set request body
[request setHTTPBody:body];
//return and test
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#", returnString);
}
Try to use this for both video and image data with different mime types.
NSDictionary *param;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
// 1. Create `AFHTTPRequestSerializer` which will create your request.
AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
NSMutableURLRequest *request;
NSData *fileData;
if ([objDoc.url containsString:#".mp4"]) {
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"application/json"];
[serializer setValue:#"video/mp4" forHTTPHeaderField:#"Content-Type"];
manager.requestSerializer = serializer;
}
// 2. Create an `NSMutableURLRequest`.
NSLog(#"filename =%#",objDoc.url);
request= [serializer multipartFormRequestWithMethod:#"POST" URLString:strUrl parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if ([objDoc.url containsString:#".mp4"]) {
[formData appendPartWithFileData:fileData
name:#"File"
fileName:#"video.mp4"
mimeType:#"video/mp4"];
}else{
[formData appendPartWithFileData:fileData
name:#"File"
fileName:#"image.jpeg"
mimeType:#"image/jpeg"];
}
} error:nil];
// 3. Create and use `AFHTTPRequestOperationManager` to create an `AFHTTPRequestOperation` from the `NSMutableURLRequest` that we just created.
self.objeDocument.isUploading = [NSNumber numberWithInt:1];
self.operation = [manager HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Error!" message:#"The document attached has failed to upload." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
[self.operation cancel];
NSLog(#"Failure %#", error.description);
}];
// 4. Set the progress block of the operation.
[self.operation setUploadProgressBlock:^(NSUInteger __unused bytesWritten,
long long totalBytesWritten,
long long totalBytesExpectedToWrite) {
NSLog(#"Wrote %lld/%lld", totalBytesWritten, totalBytesExpectedToWrite);
float progress = (float)totalBytesWritten/(float)totalBytesExpectedToWrite;
}];
// 5. Begin!
[self.operation start];
I struggled with this for a while, if you are looking for uploading multiple images or any other file types, you can do the following using AFNetworking 3.0
NSDictionary *params = #{key : value,
..... etc
};
NSString *urlString = #"http://..... your endpoint url";
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer]; // only needed if the server is not returning JSON;
NSURLSessionTask *task = [manager POST:urlString parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
for (int x = 0 ; x< contentArray.count; x++) {
AttachmentsModel *model = contentArray[x];
if(model.type == ImageAttachmentType){
[formData appendPartWithFileData:model.data name:model.name fileName:model.fileName mimeType:model.mimeType];
}else if(model.type == AudioAttachmentType){
NSURL *urlVideoFile = [NSURL fileURLWithPath:model.path];
[formData appendPartWithFileURL:urlVideoFile name:model.name fileName:model.fileName mimeType:model.mimeType error:nil];
}else{
[formData appendPartWithFileURL:model.url name:model.name fileName:model.fileName mimeType:model.mimeType error:nil];
}
}
} progress:nil success:^(NSURLSessionTask *task, id responseObject) {
[Utility stopLoading];
NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"result = %#", result);
id json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
if (block) {
//your response comes here
}
} failure:^(NSURLSessionTask *task, NSError *error) {
NSLog(#"error = %#", error);
}];
if (!task) {
NSLog(#"Creation of task failed.");
}
And here is how my AttachmentsModel looks like:
// AttachmentsModel.h
typedef enum AttachmnetType{
ImageAttachmentType,
AudioAttachmentType,
VideoAttachmentType
} AttachmnetType;
#interface AttachmentsModel : NSObject
#property (strong, nonatomic) NSString *path;
#property (strong, nonatomic) NSData *data;
#property (strong, nonatomic) NSString *mimeType;
#property (strong, nonatomic) NSString *name;
#property (strong, nonatomic) NSString *fileName;
#property (strong, nonatomic) NSURL *url;

How to send image attachment to server in post data iOS objective c

Send data to server works in postman but getting error in Objective-C.
I tried to achieve this one failed from server. I referred below links does not work. Getting error upload failed. What am I doing wrong?
Upload image to server ios
how to POST value while uploading image in iOS objective c
My Code:
NSData *dataImage = UIImageJPEGRepresentation(myImage, 1.0f);
// set your URL Where to Upload Image
NSString *urlString = #"http://xxxxxxxxxxxxxxxx/index.php/API/uploadClaim";
NSDictionary *user = [[NSUserDefaults standardUserDefaults] objectForKey:#"userDetails"];
// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:#"filename" forKey:#"file_name"];
[_params setObject:#"photo" forKey:#"file_type"];
[_params setObject:[[user objectForKey:#"user_data"] objectForKey:#"id"] forKey:#"user_id"];
NSString *BoundaryConstant = #"----------V2ymHFg03ehbqgZCaKO6jy";
NSString* FileParamConstant = #"image";
NSURL* requestURL = [NSURL URLWithString:urlString];
// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:120];
[request setHTTPMethod:#"POST"];
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]];
}
// add image data
if (dataImage) {
[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:dataImage];
[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
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// set URL
[request setURL:requestURL];
NSURLResponse *response = nil;
NSError *requestError = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:&requestError];
Here is my working code to upload one or multiple image files:
Please note: you should pass images/files data in an NSDictionary with proper key values & You should set key name as your server expecting in upload call.
For example in your case it is file
parameters dictionary will be your other parameters to send with file
- (void) performNetworkEventRequestCallWithFileUpload :(NSMutableDictionary*) imagesData : (NSMutableDictionary*)parameters completionBlock:(void (^)(BOOL succeeded, NSDictionary *dict))completionBlock {
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] init];
[urlRequest setURL:[NSURL URLWithString:BASE_URL]];
[urlRequest setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[urlRequest addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[parameters enumerateKeysAndObjectsUsingBlock: ^(NSString *key, NSString *object, BOOL *stop) {
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n",key] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",object] dataUsingEncoding:NSUTF8StringEncoding]];
}];
[imagesData enumerateKeysAndObjectsUsingBlock: ^(NSString *key, NSData *object, BOOL *stop) {
if ([object isKindOfClass:[NSData class]]) {
if (object.length > 0) {
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *timeSTamp = [NSString stringWithFormat:#"%#",[NSDate date]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"%#.jpg\"\r\n",key,timeSTamp] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:object]];
}
}
}];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[urlRequest setHTTPBody:body];
AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = nil;
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:urlRequest completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
completionBlock (NO, responseObject);
} else {
NSLog(#"success");
completionBlock (YES, responseObject);
}
}];
[dataTask resume];
}
Here i am using Afnetworking for Uplaoding image us Multipart format, its working fine. So, check it. If its ok for you just vote my answer.
#import "AFHTTPSessionManager.h"
{
NSData * profileData;
}
profileData = UIImageJPEGRepresentation(chosenImage, 1.0);
-(void)UploadImageApi
{
NSString *URLString = #“YourURL”;
/*Profile data is nothing your pick image from gallery or Camera, That saving in profile data.*/
NSMutableDictionary *parameter=[[NSMutableDictionary alloc]init];
[parameter setObject:#“yourObj” forKey:#“YourKey”];
[parameter setObject:#“yourObj” forKey:#“YourKey”];
[parameter setObject:#“yourObj” forKey:#“YourKey”];
if(profileData==nil)
{
[parameter setObject:#"" forKey:#“YourKey”];
}
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] init];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
manager.responseSerializer = [AFJSONResponseSerializer
serializerWithReadingOptions:NSJSONReadingAllowFragments];
[manager POST:URLString parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
if(profileData!=nil)
{
[formData appendPartWithFileData:profileData name:#“YourKeyName” fileName:#"filename.jpg" mimeType:#"image/jpeg"];
}
}
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"%#",responseObject);
NSMutableArray *json = [responseObject mutableCopy];
NSLog(#" success = %#",json);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"%#",error);
}];
}
you can use much simpler approach for data as well as for image:
NSDictionary *headers = #{ #"content-type": #"multipart/form-data; boundary=---------------------------14737809831466499882746641449",
#"cache-control": #"no-cache" };
NSMutableArray *parameters = [[NSMutableArray alloc]initWithObjects:#"param1",#"param2", nil];
NSMutableArray *values = [[NSMutableArray alloc]initWithObjects:#"value1",#"value2", nil];
NSString *boundary = #"---------------------------14737809831466499882746641449";
//NSData *dataImage = UIImageJPEGRepresentation(imageView.image, 1.0f); uncomment for image
NSMutableData *body = [NSMutableData data];
for (int i=0;i<parameters.count;i++) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n",[parameters objectAtIndex:i]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",[values objectAtIndex:i]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}
NSLog(#"Parameters : %#",parameters);
NSLog(#"Values : %#",values);
//image
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"image\"; filename=\"file.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
//[body appendData:[NSData dataWithData:dataImage]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://your API URL here"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:body];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"%#", error);
} else {
NSMutableArray *array=[[NSMutableArray alloc]init];
rowBtnTableLast2=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
NSLog(#"PostMethod Result : %#, PostMethod Error : %#",array,error);
}}];
[dataTask resume];

How to upload multiple images in ios?

I have tried this code to implement multiple images in iOS. Didn't work as I wanted:
NSString *BoundaryConstant = #"----------V2ymHFg03ehbqgZCaKO6jy";
// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ
NSString* FileParamConstant = #"fileToUpload[]";
NSArray *arrayfile=[NSArray arrayWithObjects:FileParamConstant,FileParamConstant ,nil];
// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:#"http://jackson.amtpl.in/tranzop/api/customertest/postorder"];
// 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=%#", 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]];
}
for (int i=0; i<upload_img_array.count; i++) {
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:[upload_img_array objectAtIndex:0]],1); // add image data
// NSData *imageData = UIImageJPEGRepresentation([upload_img_array objectAtIndex:i], 1.0);
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"image%d.png\"\r\n", FileParamConstant,i] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: image/png\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]];
}
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// set
Use this:
-(void)uploadImages{
// image.finalImage - is image itself
// totalCount - Total number of images need to upload on server
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSDictionary *parameters = #{#"Key":#"Value",#"Key":#"Value"};
[manager POST:serverURL parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:UIImagePNGRepresentation(image.finalImage) name:#"ImageName" fileName:[[Helper getRandomString:8] stringByAppendingString:#".png"] mimeType:#"image/png"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:(NSData *)responseObject options:kNilOptions error:nil];
_uploadCounter+=1;
if(_uploadCounter<totalCount){
[self uploadImages];
}else {
NSLog(#"Uploading all images done");
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error");
}];
}
This tutorial will help you:
https://charangiri.wordpress.com/2014/09/22/how-to-upload-multiple-image-to-server/
try
//img_send is a UIImage with u want to send
NSData *imageData = UIImagePNGRepresentation(img_send);
str_img= [imageData base64EncodedStringWithOptions:0];
NSDictionary *post_dir = [[NSMutableDictionary alloc] init];
[post_dir setValue:str_img forKey:#"image_string"];
NSData *jsData = [NSJSONSerialization dataWithJSONObject:post_dir options:NSJSONWritingPrettyPrinted error:nil];
NSMutableData *data = [[NSMutableData alloc] init];
self.receivedData = data;
NSURL *url = [NSURL URLWithString:#"YOUR URL STRING"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]];
//set http method
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [jsData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:jsData];
//initialize a connection from request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
self.connection=connection;
//start the connection
[connection start];
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *respData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"~~~~~ Status code: %d", [response statusCode]);
});

Migrating from NSURLConnection to NSURLSession

I am trying to migrate to NSURLSession so I can send multiple images to my server and stop when I get the needed response. But my completion block never gets called. Would appreciate if you could tell me if I am doing the migration correctly.
Here is my old code that works fine-
-(void) sendImgWithText:(UIImage*)img
{
NSURL *requestURL = [NSURL URLWithString:#"Some URL"];
// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"*****";
NSString *lineEnd = #"\r\n";
NSString *twoHyphens = #"--";
// 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)
// UIImage *imgColor = [UIImage imageNamed:#"9.jpg"];
UIImage * imageToPost = [[UIImage alloc] init];
UIImageWriteToSavedPhotosAlbum(imageToPost, nil, nil, nil);
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0);
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"%#%#%#", twoHyphens,boundary, lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"test.jpg\"%#",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
// [body appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"%#",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"%#%#%#%#", twoHyphens,boundary, twoHyphens,lineEnd] 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"];
NSLog(#"%#",requestURL);
NSLog(#"%f,%f",imageToPost.size.height,imageToPost.size.height);
// set URL
[request setURL:requestURL];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
And here is the version(I got most of it from other stack overflow articles)
- (void) serverRequestWithImage:(UIImage *)img completion:(void (^)(id responseObject, NSError *error))completion
{
NSURL *requestURL = [NSURL URLWithString:#"Some URL"];
// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"*****";
NSString *lineEnd = #"\r\n";
NSString *twoHyphens = #"--";
// 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];
UIImage * imageToPost = [[UIImage alloc] init];
imageToPost = img;
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0);
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"%#%#%#", twoHyphens,boundary, lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"test.jpg\"%#",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
// [body appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"%#",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"%#%#%#%#", twoHyphens,boundary, twoHyphens,lineEnd] 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"];
NSLog(#"%#",requestURL);
NSLog(#"%f,%f",imageToPost.size.height,imageToPost.size.height);
// set URL
[request setURL:requestURL];
NSURLSessionTask *task =
[session
dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
// report any network-related errors
NSLog(#"Got Response 1");
if (!data) {
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(nil, error);
});
}
return;
}
// report any errors parsing the JSON
NSError *parseError = nil;
_responseData = [NSMutableData dataWithData:data];
if (_responseData) {
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(nil, parseError);
});
}
return;
}
// if everything is ok, then just return the JSON object
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(_returnedData, nil);
});
}
}];
[task resume];
}
And here is my call method from the other class
- (IBAction)GetData:(id)sender
{
[_imageView setImage:[UIImage imageNamed:#"9.jpg"]];
msg = [[Message alloc] init];
[msg initData];
msg.delegate=self;
[msg serverRequestWithImage:_imageView.image completion:^(id responseObject, NSError *error)
{
if (responseObject) {
// do what you want with the response object here
NSLog(#"Got Data");
} else {
NSLog(#"%s: serverRequest error: %#", __FUNCTION__, error);
}
}];
}
Items:
I didn't see the initialization of NSURLSession. That's something you should show in your question. You could also check in your "send image" method that session is non-nil.
It looks like you are starting with a file (#"9.jpg"). If so, -[NSURLSession uploadTaskWithRequest:fromFile:completionHandler:] might save you a bunch of trouble.
Unrequested advice, with all that entails: :)
In my view, -serverRequestWithImage:completion: is a poor name for that method. It implies that it returns a request object, and does not tell you that it actually sends the request. Something active, like -uploadImage:completionHandler: might be better.
Idiomatically, all method names should start lowercase, i.e. -getData:.

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);
}];

Resources