1
         NSMutableDictionary *files = [[NSMutableDictionary alloc] init];
           UIImage *imageFromImageView = userpic.image;

            NSData *data1 = UIImageJPEGRepresentation(imageFromImageView, 0.8);
            if ([data1 length]>0) {
                [files setValue:data1 forKey:@"photo"];
            }


    NSString *urlString =@"http://chkdin.com/dev/api/user/update_user?";
    NSURL *url = [NSURL URLWithString:urlString];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

    NSString *parameterString=[NSString stringWithFormat:@"skey=%@&user_id=%@&first_name=%@&last_name=%@&designation=%@&company=%@&display_name=%@&photo=%@",@"XXXXXXXX",[[NSUserDefaults standardUserDefaults]objectForKey:@"UserId"],FirstNameString,LastNameString,DesignationString,OrganizationString,displayname,files];

    NSLog(@"%@",parameterString);

    [request setHTTPMethod:@"POST"];
    [request setURL:url];
    [request setValue:parameterString forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    NSData *postData = [parameterString dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:postData];

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            [activityIndicatorView stopAnimating];
        } else {
            NSLog(@"%@ %@", response, responseObject);
  }
      }];
    [dataTask resume];

This is I tried code, here user selected image I upload to server but image is not uploading. Here user selected image I converted to file formate then I send to server. Can you please help me what is the issue in my code.

Siva Sankar
  • 543
  • 1
  • 4
  • 18
  • What is the issue/error? Is Server not getting the request with this file? Or the file is not getting converted to the specific format? Tell us more about the problem – saurabh Feb 02 '17 at 06:31
  • 2
    @SivaSankar : File uploading is not supported by `x-www-form-urlencoded`. You should use `multipart/form-data` to upload files into server. Check http://stackoverflow.com/questions/24250475/post-multipart-form-data-with-objective-c – Poles Feb 02 '17 at 06:34
  • i converted image to file formate, image is converted but server is not accepting – Siva Sankar Feb 02 '17 at 06:34
  • I have an answer about his way back, please check [it here](http://stackoverflow.com/questions/30796059/upload-multiple-images-to-server-ios/30796772#30796772) – 0yeoj Feb 02 '17 at 07:34
  • did you got answer @SivaSankar – Himanth Feb 03 '17 at 05:50
  • bellow answer is not working. – Siva Sankar Feb 03 '17 at 05:51
  • 1
    download demo and see : https://github.com/IosPower/WebserviceSwift3 – Piyush Sinroja Feb 03 '17 at 06:41

4 Answers4

0

You should use multipart/form-data to upload files into server. Try this:

NSMutableDictionary *params=[NSMutableDictionary dictionary];
[params setObject:@"sa6rw9er7twefc9a7dvcxcheckedin" forKey:@"skey"];
[params setObject:[[NSUserDefaults standardUserDefaults]objectForKey:@"UserId"] forKey:@"user_id"];
[params setObject:FirstNameString forKey:@"first_name"];
[params setObject:LastNameString forKey:@"last_name"];
[params setObject:DesignationString forKey:@"designation"];
[params setObject:OrganisationString forKey:@"company"];
[params setObject:displayname forKey:@"display_name"];

NSError *error = nil;

NSData *jsonData=[NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[jsonData length]];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://chkdin.com/dev/api/user/update_user"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:180];

[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

//Post value as form data

NSMutableData *body = [NSMutableData data];

NSString *boundary = @"---------------------------14737800031466499882746641949";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; charset=utf-8; boundary=%@", boundary];

[request addValue:contentType forHTTPHeaderField:@"Content-Type"];

[params enumerateKeysAndObjectsUsingBlock:^(NSString *parameterKey, NSString *parameterValue, BOOL *stop) {
   [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
   [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", parameterKey] dataUsingEncoding:NSUTF8StringEncoding]];
   [body appendData:[[NSString stringWithFormat:@"%@\r\n", parameterValue] dataUsingEncoding:NSUTF8StringEncoding]];
}];

//Image upload part
UIImage *imageFromImageView = userpic.image;

NSData *dataImage = UIImageJPEGRepresentation(imageFromImageView, 0.8);

[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: attachment; name=\"photo\"; filename=\"%@\"\r\n",@"photoname"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: image/jpg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:dataImage];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

//close the form
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            [activityIndicatorView stopAnimating];

        } else {
            NSLog(@"%@ %@", response, responseObject);
        }
}];
[dataTask resume];
Poles
  • 3,585
  • 9
  • 43
  • 91
  • sorry for late reply, here app is crashing [body appendData:[NSData dataWithContentsOfFile:dataImage]]; – Siva Sankar Feb 03 '17 at 05:38
  • [NSConcreteMutableData getFileSystemRepresentation:maxLength:]: unrecognized selector sent to instance 0x170458f00' – Siva Sankar Feb 03 '17 at 05:38
  • @SivaSankar : Please see the updated code. Actually I forgot to remove that portion where you are getting crash. I mistakenly converting `NSData` to `NSData`. It should be `dataImage` directly. – Poles Feb 03 '17 at 06:39
0

Try this:

NSMutableDictionary *files = [[NSMutableDictionary alloc] init];
           UIImage *imageFromImageView = userpic.image;

            NSData *data1 = UIImageJPEGRepresentation(imageFromImageView, 0.8);
            if ([data1 length]>0) {
                [files setValue:data1 forKey:@"photo"];
            }


        NSString *Datestr = [self dateStringJPG];
        NSString *str=@"http://chkdin.com/dev/api/user/update_user?";

        NSString *parameterString=[NSString stringWithFormat:@"skey=%@&user_id=%@&first_name=%@&last_name=%@&designation=%@&company=%@&display_name=%@&photo=%@",@"sa6rw9er7twefc9a7dvcxcheckedin",[[NSUserDefaults standardUserDefaults]objectForKey:@"UserId"],FirstNameString,LastNameString,DesignationString,OrganizationString,displayname,files];

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        NSString *BoundaryConstant = @"----------V2ymHFg03ehbqgZCaKO6jy";
        NSString* FileParamConstant = @"file";
        NSURL* requestURL = [NSURL URLWithString:str];
        request = [[NSMutableURLRequest alloc] init];
        [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
        [request setHTTPShouldHandleCookies:NO];
        [request setTimeoutInterval:60];
        [request setHTTPMethod:@"PUT"];
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant];
        [request setValue:contentType forHTTPHeaderField: @"Content-Type"];
        NSMutableData *body = [NSMutableData data];

        NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
        if (imageData) {
            [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:imageData];
            [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        }
        [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
   NSData *postData = [parameterString dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:postData];        
        NSString *postLength = [NSString stringWithFormat:@"%d", [body length]];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setURL:requestURL];
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
            if(data.length > 0)
            {
                NSLog(@"success jpg %@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
            }
            else
            {
                NSLog(@"---xxerror %@-%@",data,error);
            }
        }];
Himanth
  • 2,381
  • 3
  • 28
  • 41
0
-(void)sendDataToServer
{
indicators.hidden=NO;
[indicators startAnimating];
 NSUserDefaults*defaults=[NSUserDefaults standardUserDefaults];

dict = [defaults objectForKey:@"Ucountry"];

NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
    [_params setObject:[dict objectForKey:@"id"]  forKey:@"userId"];

[_params setObject:@""  forKey:@"address"];
[_params setObject:txtCity.text  forKey:@"city"];
[_params setObject:@""  forKey:@"country"];
[_params setObject:txtemail.text  forKey:@"emailId"];
[_params setObject:txtFullName.text  forKey:@"firstName"];
[_params setObject:txtPhoneNumber.text  forKey:@"mobile"];
[_params setObject:txtState.text  forKey:@"state"];
[_params setObject:txtZipCode.text  forKey:@"zipcode"];


DLog(@"data=====>%@",_params);
[_params setObject:@"editprofile"  forKey:@"action"];


NSString *BoundaryConstant = @"----------V2ymHFg03ehbqgZCaKO6jy";
NSString* FileParamConstant = @"image";

NSURL* requestURL = [NSURL URLWithString:BaseURL];


// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[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 (imageData) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:imageData];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}

[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];

// setting the body of the post to the reqeust
[request setHTTPBody:body];

// set the content-length
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];


if (requestError == nil)
{

    NSDictionary* json = [NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:&requestError];

    dict=json;
    DLog(@"data=====>%@",dict);

    if ([[dict objectForKey:@"status"] isEqualToString:@"Success"]==TRUE)
    {
        [hud hideAnimated:YES];


        NSUserDefaults *defUser = [NSUserDefaults standardUserDefaults];
        [defUser setObject:[dict objectForKey:@"response"]forKey:@"Ucountry"];
        [defUser synchronize];

        UIStoryboard*storyboard=[AppDelegate storyBoardType];
        DashboardVC*dsvc=(DashboardVC*)[storyboard instantiateViewControllerWithIdentifier:@"DashboardVCId"];
        [self.navigationController pushViewController:dsvc animated:YES];
                }else{
                    [hud hideAnimated:YES];

    }
}
}
 -(void)Open_Camera{

#if TARGET_IPHONE_SIMULATOR

NSLog(@"No Camera is set up in Simulator");

#else

UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:picker animated:YES completion:NULL];

#endif

}

-(void)Open_Library{

UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];

imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.delegate=self;
imagePicker.navigationBar.tintColor=[UIColor whiteColor];
imagePicker.allowsEditing = YES;

if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
{
    [self presentViewController:imagePicker animated:YES completion:nil];
}
else{
    [self presentViewController:imagePicker animated:YES completion:nil];
}
}

-(void)selectphoto{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {


   UIImage *img =   [info objectForKey:UIImagePickerControllerOriginalImage];
imgView.image =img;
NSLog(@"image user png is -----<%@",imgView.image);

if(imgView==nil)
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"OOPS" message:@"No Image Foundy "
                                                                      preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:actionOk];
    [self presentViewController:alertController animated:YES completion:nil];

}
else
{
    imageData=[self compressImage:img];

    [picker dismissViewControllerAnimated:YES completion:nil];

}
return;

}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {

[picker dismissViewControllerAnimated:YES completion:NULL];

}

-(NSData *)compressImage:(UIImage *)image1 {

float actualHeight = image1.size.height;
float actualWidth = image1.size.width;
float maxHeight = 500.0;
float maxWidth = 500.0;
float imgRatio = actualWidth/actualHeight;
float maxRatio = maxWidth/maxHeight;
float compressionQuality = 0.5;

if(imgRatio < maxRatio){

    imgRatio = maxHeight / actualHeight;
    actualWidth = maxWidth;
    actualHeight = maxHeight;
}
else if(imgRatio > maxRatio){

    imgRatio = maxWidth / actualWidth;
    actualHeight = maxHeight;
    actualWidth = maxWidth;
}
else{
    actualHeight = maxHeight;
    actualWidth = maxWidth;
}
CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
UIGraphicsBeginImageContext(rect.size);
[image1 drawInRect:rect];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
imageData = UIImageJPEGRepresentation(img, compressionQuality);
UIGraphicsEndImageContext();

return imageData;
}
-(IBAction)actionSheetForCameraAndGalleryClick:(id)sender{
    UIAlertController*alertAction=[UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];

    UIAlertAction *action=[UIAlertAction actionWithTitle:@"Camera" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){

        [self Open_Camera];
    }];


    UIAlertAction *action1=[UIAlertAction actionWithTitle:@"Gallery" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){

        [self Open_Library];
    }];


    UIAlertAction *cancelAlert=[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){


        [self dismissViewControllerAnimated:YES completion:nil];
    }];


    [alertAction addAction:action];
    [alertAction addAction:action1];
    [alertAction addAction:cancelAlert];

    [self presentViewController:alertAction animated:YES completion:nil];
}
- (IBAction)CameraOpena:(id)sender {

[self Open_Camera];
}

- (IBAction)GalleryOpen:(id)sender {

[self Open_Library];
}
Dishant Rajput
  • 1,329
  • 1
  • 10
  • 20
0

Write a api Request method like this, using Afnetworking...

-(void)apiRequestImageUploadWithCompleteBlock:(NSString *)methodName methodParameters:(NSDictionary *)methodParameters imageName:(NSString *)imageName uploadImageData:(NSData *)uploadImageData inputParameters:(NSDictionary *)inputParameters completeBlock:(RTDictionaryResponseBlock)completeBlock failBlock:(RTFailBlock)failBlock
{
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    //AFHTTPSessionManager *session = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    session.requestSerializer = [AFJSONRequestSerializer serializer];
    [session.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

    //--------------------------------------------------------------------------------------
NSString *URL_String = [NSString stringWithFormat:@"%@",baseUrl];

        NSDictionary *params = @{
                                 @"securitykey”:@“”,
                                 @"fc":@"",
                                 @"module":@""
                                 };

        NSMutableDictionary *dict_parameters=[params mutableCopy];
        [dict_parameters addEntriesFromDictionary:inputParameters];

        //Add method parameters
        [dict_parameters addEntriesFromDictionary:methodParameters];



        [session POST:URL_String parameters:dict_parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

            [formData appendPartWithFileData:uploadImageData name:@"image" fileName:imageName mimeType:@"image/png"];

        } progress:^(NSProgress * _Nonnull uploadProgress) {

        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

            NSDictionary *dataObj = (NSDictionary *)responseObject;

            completeBlock(dataObj);

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

            NSLog(@"%s :%@",__PRETTY_FUNCTION__,error.description);

            failBlock();
        }];
   }     
Sathish Kumar VG
  • 2,154
  • 1
  • 12
  • 19