0

I'm trying to upload an image using AFNetworking library, its a post request, the image should be in the body. i converted it to NSData and tried to send it, but it didn't work, all what I got from the backend guy that the image form should be as image file.

My code is below:

+(void)imageUpload:(NSMutableDictionary *)imageData :(void(^)(BOOL success,NSError *error,NSString *path))block{
    NSString *urlString = [baseUrl stringByAppendingString:@"Media/ImageUpload"];
    NSMutableDictionary *parameters = [NSMutableDictionary new];
    [parameters setObject:[self getXsession] forKey:@"x-session"]; 
    UIImage *image = [imageData objectForKey:@"image"];
    NSData *imgData = UIImagePNGRepresentation(image);
    NSMutableDictionary *bodyImage = [NSMutableDictionary new];
    [bodyImage setObject:imgData forKey:@"image"];
    [bodyImage setObject:@"leads_temp" forKey:@"folder"];
    [self makePostRequestWithUrl:urlString parameters:parameters body:bodyImage headers:nil updateXsession:NO completionBlock:^(NSError *error, id responseObject) {
        BOOL success = [responseObject[@"meta"][@"status"]isEqualToString:@"OK"]?YES:NO;
        if(success){
            NSString *path = responseObject[@"response"][@"path"];
            if (block){
                block(success,nil,path);
            }
        }else {
            if (block){
                block(NO,error,nil);
            }
        }
    }];
}

Post request:

+(void)makePostRequestWithUrl:(NSString *)url parameters:(NSMutableDictionary *)parameters body:(NSMutableDictionary*)body headers:(NSDictionary *)headers updateXsession:(BOOL)shouldUpdate completionBlock:(void(^)(NSError *error, id responseObject))block {
    NSError *error;
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:parameters error:&error];
    request.timeoutInterval = 30;

        NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:body options:NSJSONWritingPrettyPrinted error:&error];
        NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
  stringWithFormat:@"%@\n%@\n%@",tableValue,jsonString,@"}"];
    [request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        NSHTTPURLResponse *myResponse = (NSHTTPURLResponse *)response ;
        if (myResponse && shouldUpdate) {
           //do some stuffs
        }
        if (block) {
            block(error, responseObject);
        }else {
            block(responseObject, error);
            return ;

        }
    }]resume];
}

Any idea what the solution could be? thanks.

Sunil Targe
  • 7,251
  • 5
  • 49
  • 80
MrJ
  • 96
  • 10
  • I had similar problem: https://stackoverflow.com/questions/40058781/afnetworking-send-image-as-file-not-as-data – Stefan Jul 31 '18 at 09:38
  • 3
    @Stefan It's not good idea to convert `UIImage` to UTF8 string. you can upload `UIImage` by multipart. – Kuldeep Jul 31 '18 at 09:40
  • @Kuldeep via multipart it will be chunk of bits(Data). Server is expecting IMAGE not DATA – Stefan Jul 31 '18 at 09:41
  • @Stefan, no chunk at all. – Kuldeep Jul 31 '18 at 09:43
  • https://github.com/mikeho/QSUtilities/blob/master/QSStrings.h I guess there's a valid reason why there is whole library that is tool for converting images to Bas64, or it's a big error? – Stefan Jul 31 '18 at 09:43
  • Then give a solution and make a light on a dark road. – Stefan Jul 31 '18 at 09:44
  • And `NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:body options:NSJSONWritingPrettyPrinted error:&error];` doesn't give an error? Because you have a an object that is a `NSData` in `body`, and clearly that shouldn't be allowed. – Larme Jul 31 '18 at 09:45
  • @Stefan Look at this : https://stackoverflow.com/questions/14788130/base64-image-upload-vs-binary-image-upload/14789376. https://stackoverflow.com/questions/47095294/what-is-difference-between-base64-and-multipart – Kuldeep Jul 31 '18 at 09:59
  • converting image to utf8 stirng didnt work, it returned nil – MrJ Jul 31 '18 at 09:59

1 Answers1

1

Try this.

-(void)uploadImage1:(UIImage *)img Dictionary:(NSMutableDictionary *)dictParam {
    NSData *imageData;
    if (img == nil) {

    }
    else {
        imageData = UIImageJPEGRepresentation(img, 0.7); // IF you want to compress image
    }

    AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
    AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];

    requestSerializer = [AFJSONRequestSerializer serializer];
    responseSerializer = [AFJSONResponseSerializer serializer];

    NSError *__autoreleasing* error = NULL;

    NSMutableURLRequest *request = [requestSerializer multipartFormRequestWithMethod:@"POST" URLString:"YOUR_URL" parameters:dictParam constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if (imageData != nil) {
            [formData appendPartWithFileData:imageData
                                        name:@"profile_image" // Name of your Image Param
                                    fileName:@"user_image.jpg"
                                    mimeType:@"image/jpg"];
        }
    } error:(NSError *__autoreleasing *)error];

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

    manager.responseSerializer = responseSerializer;

    NSURLSessionUploadTask *uploadTask;
    uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {

    }
                                      completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                                          if (error) {
                                              [SVProgressHUD dismiss];
                                              NSLog(@"ERROR = %@",error.localizedDescription);
                                          }
                                          else {
                                              if ([[responseObject valueForKey:@"status"] intValue] == 1) {
                                                  NSLog(@"SUCCESS");
                                              }
                                              else {
                                                  NSLog(@"ERROR FROM SERVER = %@", [responseObject valueForKey:@"message"]);
                                              }
                                          }
                                      }];

    [uploadTask resume];
}
Kuldeep
  • 4,466
  • 8
  • 32
  • 59