AFNetworking send image as file not as data

2019-06-06 10:40发布

问题:

Hi server that I'm sending data is expecting image as file(jpg) not as NSData. This code works, but server can't recognize NSData as image. Any thoughts how to solve this?

+ (void)signupWithParameters:(NSDictionary *)parameters
            andUserHaveImage:(BOOL)userHaveImage
                    andImage:(NSData *)image
                successBlock:(void (^) (NSDictionary *response))successHandler
                  errorBlock:(void (^) (NSDictionary *error))errorHandler
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setValue:@"multipart/form­data" forHTTPHeaderField:@"Content-Type"];


    [manager POST:[NSString stringWithFormat:@"%@/api/1.0/customer/sign-up", DEFAULT_URL] parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if (userHaveImage == YES) {
//  

      [formData appendPartWithFileData:image name:@"img_profile" fileName:@"profileImage.jpg" mimeType:@"image/jpg"];
        [formData appendPartWithFormData:image name:@"img_profile"];
    }

} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    successHandler(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    errorHandler(@{});
}];

}

回答1:

Solved by converting image to UTF8 string and sending it in that format.