使用 AFNetworking 上传图像

Uploading images using AFNetworking

我正在尝试使用 AFNetworking 库上传图片,这是一个 post 请求,图片应该在正文中。我将它转换为 NSData 并尝试发送它,但它没有用,我从后端人员那里得到的所有信息都是图像形式应该是图像文件。

我的代码如下:

+(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 请求:

+(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];
}

知道解决方案是什么吗? 谢谢。

试试这个。

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