Upload an image after 64-bit encoding - ios

I want to upload an image on a server. I encode to 64-bit then I post. I am using this code:
NSURL *url=[[NSURL alloc] initWithString:#"http://boomagift.ramansingla.com/userpicture.php?email=sonal#gmail.com"];
NSMutableURLRequest *req=[[NSMutableURLRequest alloc] initWithURL:url];
[req setHTTPMethod:#"POST"];
// [req setValue:#"multipart/form-data; boundary=*****" forHTTPHeaderField:#"Content-Type"];
NSMutableData *postBody=[NSMutableData data];
NSString *boundary=#"*****";
[postBody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"test.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
NSString *this=[pickedImageData base64EncodedString];
[postBody appendData: [this dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[req setHTTPBody:postBody];
NSHTTPURLResponse *response=nil;
NSError *error=[[NSError alloc] init];
NSData *responseData;
responseData=[NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
NSLog(#"%#",responseData);
if(responseData&&[responseData length])
{
NSDictionary *dictionary=[NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
NSLog(#"%#",dictionary);
}
else
{
NSLog(#"hello");
}

-(NSArray *)getResizedUImage:(UIImage *)getImage otherValueOne:(float)newWidth otherValueSecond:(float)newHeight
{
CGRect rect = CGRectMake(0.0, 0.0, newWidth, newHeight);
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 1);
[getImage drawInRect:rect];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSArray *loadImageDateArray = [[NSArray alloc]init];
UIImage *imageConvert = img;
NSData *data = UIImageJPEGRepresentation(imageConvert, 0.8);
NSString *base64String = [data base64EncodedStringWithOptions:0];
loadImageDateArray = [NSArray arrayWithObject:base64String];
return loadImageDateArray;
}
This code part return base 64 try this
I update my answer use this function, this function return base 64

Related

How to post multiple images using multipart / formdata in objective c

I am trying to post two images to an url using multipart post request in Objective C , From my code I can able to send only one image, How to send two images to the url, using multipart / form data I have tried so many example for this bur I did not get the result I want
-(void)processPostMultipartRequestNew{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSString *urlStr = [self.dataModel.apiUrl
stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
urlStr = [urlStr
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
urlStr= [urlStr stringByReplacingOccurrencesOfString:#"+" withString:#"%2B"];
NSURL *reqUrl = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:reqUrl];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSDictionary *requestBody = self.dataModel.requestParams2;
UIImage *imageToUpload = [requestBody objectForKey:keyUploadImage];
NSDictionary *requestBody2 = self.dataModel.requestParams;
UIImage *imageToUpload2 = [requestBody2 objectForKey:keyUploadImage];
if(requestBody){
NSData *imageData = UIImageJPEGRepresentation(imageToUpload, 0);//no compression by default
NSData *imageData2 = UIImageJPEGRepresentation(imageToUpload2, 0);
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: attachment; name=\"uploadedfile1\"; filename=\".jpeg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: attachment; name=\"uploadedfile2\"; filename=\".jpeg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[NSData dataWithData:imageData2]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// Text parameter1
NSString *param1 = #"111";
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"SyncId\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:param1] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
}
[request setHTTPShouldHandleCookies:NO];
[request setHTTPMethod:REQUEST_TYPE_POST];
[request setTimeoutInterval:60*4];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSLog(#"completionHandler with response:%#",[NSHTTPURLResponse localizedStringForStatusCode:[(NSHTTPURLResponse*)response statusCode]]);
NSLog(#"reponse: %ld",(long)[(NSHTTPURLResponse*)response statusCode]);
NSInteger status = [(NSHTTPURLResponse*)response statusCode];
if(error){
NSLog(#"http request error: %#", error.localizedDescription);
// handle the error
}
else{
if (status == 201){
// handle the success
}
else{
NSLog(#"error");
} // handle the error
}
if(!data || data == nil)
return ;
NSLog(#"%#",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
NSDictionary *resultDict =(NSDictionary *) [NSJSONSerialization
JSONObjectWithData:data options:NSJSONReadingAllowFragments
error:&error];
//NSDictionary *resultDict =(NSDictionary *) [NSJSONSerialization JSONObjectWithStream:data options:kNilOptions error:&error];
self.dataModel.responseData =resultDict;
NSLog(#"error is %#",error);
NSLog(#"data is %#",data);
{
if(!data || data == nil)
return ;
NSLog(#"%#",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
//for failed case
if(error || error != nil){
self.dataModel.responseFailed = YES;
self.dataModel.error = error;
NSLog(#"Result in error case %#",[[error userInfo] objectForKey:#"NSDebugDescription"]);
[self.reciever performSelectorOnMainThread:self.callBack withObject:self.dataModel waitUntilDone:YES];
}
else{
self.dataModel.responseFailed = NO;
self.dataModel.error = nil;
NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if(!([response rangeOfString:#".jpg"].location==NSNotFound))
{
NSString *res=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
self.dataModel.responseData =res;
[self.reciever performSelectorOnMainThread:self.callBack withObject:self.dataModel waitUntilDone:YES];
}
}
}
self.executing = NO;
[self setFinishedState:YES];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
[self.reciever performSelectorOnMainThread:self.callBack withObject:self.dataModel waitUntilDone:YES];
}];
}
Is this a right way to do? if not how can I get success in this. Thanks in advance.
Yes you can like this
Edit
///////////////////////////////
// Dictionary that holds post parameters. You can set your post parameters that your server accepts or programmed to accept.
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:#"ios" forKey:#"device_type"];
[_params setObject:#"user" forKey:#"type"];
[_params setObject:"iddddd" forKey:#"user_id"];
// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
NSString *BoundaryConstant = #"----------V2ymHFg03ehbqgZCaKO6jy";
// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ
// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:#"http........"];
// 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 allKeys]) {
[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 txt data
/////////////////////////////
NSArray *allImagesData= #[UIImagePNGRepresentation(imageToUpload) ,UIImagePNGRepresentation(imageToUpload2)];
NSLog(#"files array before %#", allImagesData);
for (int i=0; i<[allImagesData count]; i++)
{
NSString*filename=[NSString stringWithFormat:#"image%d.jpeg",i+1];
NSString* FileParamConstant = [NSString stringWithFormat:#"image%d",i+1];
NSData *imageData = allImagesData[i];
if (imageData)
{
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"%#\"\r\n", FileParamConstant,filename] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
}
U can do like this:
-(void)PostUrlCall_Multipart_Image:(NSString *)IN_URL Param:(NSDictionary*)IN_Param Image:(UIImage *)image
{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/json"];
[manager POST:IN_URL parameters:IN_Param constructingBodyWithBlock:^(id<AFMultipartFormData> formData){
[formData appendPartWithFileData:UIImageJPEGRepresentation(image, 1.0) name:#"image" fileName:#"image" mimeType:#"image/jpeg"];
}
progress:nil
success:^(NSURLSessionDataTask *task, id responseObject) {
m_Status=1;
self.dic_Response = (NSDictionary *)responseObject;
[[NSNotificationCenter defaultCenter] postNotificationName:m_strPostMsg object:self];
}
failure:^(NSURLSessionTask *operation, NSError *error){
m_Status=0;
self.dic_Response=[[NSMutableDictionary alloc]init];
// [self.dic_Response setValue:#[Time_Out_Msg] forKey:#"#[Time_Out_Msg]"];
NSLog(#"Error %#",error);
[[NSNotificationCenter defaultCenter] postNotificationName:m_strPostMsg object:self];
}];
}

How to upload an image from a dictionary that contains other text parametes?

I want to upload an image from a dictionary which looks like this,
{
pic_image : file attache
pic_user_id : 1
pic_name : abcd.jpg
}
where file attached is the image i want to upload from the image view, How to achieve this?
this my function to upload image that is inside a dictionary
-(void)uploadImageWithparams:(NSDictionary *)params withDelegate:(id)delegateObject withHandler:(HMResponseBlock)block{
// This isn't actually my url btw
// setting up the request object now
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#,%#",kBaseUrl,#"page=user"]]];
[request setHTTPMethod:#"POST"];
NSMutableArray *parameters = [[NSMutableArray alloc] init];
for (NSString *key in params.allKeys) {
if([key rangeOfString:#"pic_image"].location != NSNotFound){
[parameters addObject:#{#"fileName": key, #"value": params[key]}];
}else {
[parameters addObject:#{#"name": key, #"value": params[key]}];
}
}
NSLog(#"The parameters are %#",parameters);
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSError *error;
NSMutableData *body = [NSMutableData data];
for (NSDictionary *param in parameters) {
if (param[#"fileName"]) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"photo\"; filename=\"%#\"\r\n", #"abcd"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:param[#"value"]];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}else {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition:form-data; name=\"%#\"\r\n\r\n", param[#"name"]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#\r\n", param[#"value"]] dataUsingEncoding:NSUTF8StringEncoding]];
}
}
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"%#", error);
} else {
NSDictionary *json = nil;
NSError *err;
if(data){
json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&err];
}
block(json,err);
}
}];
[dataTask resume];
}
Get image name from dictionary by key name
ex:
NSString *imageName = myDictioanry[#"pic_name"];
by this code you can get image name from dictionary
UIImage *image = [UIImage imageNamed:imageName];
you can get image from image name by above code
or else you can get image from imageView and convert to NSData by below code
UIImage *image = myImageView.image;
if you want code for upload image to server, click this link
imageUploadLink

How can I send a multipart HTTP request on iOS?

I am trying to upload a photo onto a server on my iOS App using multipart method. However, I can't seem to get it to work. I am getting the error:
At least one of the pre-conditions you specified did not hold. Bucket POST must be of the enclosure-type multipart. I've looked this error and can't seem to figure out how I can solve this problem on my end. The Android version of the app works so the API should not be the problem?
Here is my code:
//photo file
NSData *data = [[NSFileManager defaultManager] contentsAtPath:filePath];
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:uploadInfo.key forKey:#"key"];
[_params setObject:uploadInfo.aaki forKey:#"AWSAccessKeyId"];
[_params setObject:uploadInfo.acl forKey:#"acl"];
[_params setObject:uploadInfo.policy forKey:#"policy"];
[_params setObject:uploadInfo.signature forKey:#"signature"];
[_params setObject:uploadInfo.success_action_status forKey:#"success_action_status"];
[_params setObject:#"image/jpeg" forKey:#"Content-Type"];
NSURL* requestURL = [NSURL URLWithString:uploadInfo.path];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
NSMutableData *body = [NSMutableData data];
for (NSString *param in _params) {
[body appendData:[[NSString stringWithFormat:#"%#", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
if (data) {
[body appendData:data];
}
[request setHTTPBody:body];
[request setURL:requestURL];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding];
NSLog(#"%#",responseString);
Try as below.
//photo file
NSData *data = [[NSFileManager defaultManager] contentsAtPath:filePath];
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:uploadInfo.key forKey:#"key"];
[_params setObject:uploadInfo.aaki forKey:#"AWSAccessKeyId"];
[_params setObject:uploadInfo.acl forKey:#"acl"];
[_params setObject:uploadInfo.policy forKey:#"policy"];
[_params setObject:uploadInfo.signature forKey:#"signature"];
[_params setObject:uploadInfo.success_action_status forKey:#"success_action_status"];
NSURL* requestURL = [NSURL URLWithString:uploadInfo.path];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
//Create boundary, it can be anything
NSString *boundary = #"------VohpleBoundary4QuqLuM1cE5lMwCy";
// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
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]];
}
NSString *FileParamConstant = #"image"; // Key of webservice in which you need to send image
// add image data
if (data) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:data];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
//Close off the request with the boundary
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setURL:requestURL];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
Try with another simple code.
NSDictionary *aParams =#{}; //your param dictionary here
UIImage *aImage = [UIImage imageNamed:#"your image here"]; //set yout image here
NSString *aStrParamName = #"image parameter name here";// set parameter name of image here
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"uploadInfo.path"]];// url here
[request setHTTPMethod:#"POST"];
[request setTimeoutInterval:30];
NSString *uuidStr = [[NSUUID UUID] UUIDString];
[request addValue:[NSString stringWithFormat:#"multipart/form-data; boundary=%#", uuidStr] forHTTPHeaderField:#"Content-Type"];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
NSData *imagedata = UIImageJPEGRepresentation(aImage, (CGFloat)0.6);
NSData *fileData = UIImagePNGRepresentation([UIImage imageWithData:imagedata]);
NSData *data = [self createBodyWithBoundary:uuidStr withDictData:aParams data:fileData filename:aStrParamName];
NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSAssert(!error, #"%s: uploadTaskWithRequest error: %#", __FUNCTION__, error);
// parse and interpret the response `NSData` however is appropriate for your app
NSString *aStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"ResponseString:%#",aStr);
NSMutableDictionary *aMutDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"responce:%#",aMutDict);
});
}];
[task resume];
also add below method
- (NSData *)createBodyWithBoundary:(NSString *)boundary withDictData:(NSDictionary *)aDict data:(NSData*)data filename:(NSString *)paramName
{
NSMutableData *body = [NSMutableData data];
if (data) {
//only send these methods when transferring data as well as username and password
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"%#\"\r\n", paramName,#"image.png"] dataUsingEncoding:NSUTF8StringEncoding]];
#warning if you have to chane name of image then change. if there is any error then chane other wise go as it is..
[body appendData:[[NSString stringWithFormat:#"Content-Type: %#\r\n\r\n", #"image/png"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:data];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}
for (NSString *aKey in aDict.allKeys) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n%#\r\n", aKey,aDict[aKey]] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
return body;
}

how to upload multiple images to server ios?

I am trying to upload Image From my IOS device to server. when upload single image file to server it is successfully uploaded to my server. i want to upload multiple image files to server how can i do this.
// COnvert Image to NSData
NSData *dataImage = UIImageJPEGRepresentation([UIImage imageNamed:#"icon.png"], 1.0f);
// set your URL Where to Upload Image
NSString *urlString = #"http://XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/imgupload.php";
// set your Image Name
NSString *filename = #"icon";
// Create 'POST' MutableRequest with Data and Other Image Attachment.
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:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#.png\"\r\n",filename] dataUsingEncoding:NSUTF8StringEncoding]]; [postbody appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:dataImage]];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];
// Get Response of Your Request
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Response %#",responseString);
Muliple images upload attempted code
-(void)uploadImageToServer:(NSArray*)arrUploadData withTreatmentDetails:(NSDictionary *)dictArguments url:(NSString*)url
{
// COnvert Image to NSData
// set your URL Where to Upload Image
NSString *urlString = #"http://XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/imgupload.php";
// set your Image Name
// Create 'POST' MutableRequest with Data and Other Image Attachment.
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];
for (int i=0; i<[arrUploadData count]; i++)
{
NSData *dataImage = [[arrUploadData objectAtIndex:i] valueForKey:#"photographyData"];
NSString *filename = [[arrUploadData objectAtIndex:i] valueForKey:#"photographyimagename"];
if (dataImage)
{
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#.png\"\r\n",filename] dataUsingEncoding:NSUTF8StringEncoding]]; [postbody appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:dataImage]];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
}
}
[request setHTTPBody:postbody];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Response %#",responseString);
}
Hello, You can do it by using NSMutableArray
For Example :
NSMutableArray *arrayImageData = [[NSMutableArray alloc]init];
Take images from imagepicker
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissViewControllerAnimated:YES completion:nil];
NSString *filePath,*path;
NSData *dataImage = UIImageJPEGRepresentation([info objectForKey:#"UIImagePickerControllerOriginalImage"],1);
[arrayImageData addObject:dataImage];
filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:#"screenShot1.png"];
[picker dismissViewControllerAnimated:YES completion:nil];
}
At the time of posting image on Server use following code
for (int i = 0; i < [arrayImageData count]; i++)
{
[request setPostValue:[[MYUtility getInstance] base64StringFromNSData:[arrayImageData objectAtIndex:i]] forKey:[NSString stringWithFormat:#"Image%d", i + 1]];
}
Hope this will help for you...I used this code for saving multiple images on server.

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