AFnetworking multipart request body is nil

2019-02-24 02:24发布

问题:

I am trying to upload picture to server, via af 2.0 multipart request, but it seems body is always null. Here is a snapshot from code:

[self POST:path parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFormData:file name:@"file"];
} success:^(NSURLSessionDataTask *task, id responseObject) {
andAPIResponseType:apiResponseType];
} failure:^(NSURLSessionDataTask *task, NSError *error) {

}];

where file is photo that i took from device camera and did something like this

 NSData *file = UIImageJPEGRepresentation(avatar, 0.5)

However when i log what i send via AF logger, i get something like this

103762376897069058/avatar?access_token=4f77072f0f7de259293f229c7a876130c79705d7': {
"Accept-Language" = "en;q=1, fr;q=0.9, de;q=0.8, ja;q=0.7, nl;q=0.6, it;q=0.5";
"Content-Length" = 29120;
"Content-Type" = "multipart/form-data; boundary=Boundary+0xAbCdEfGbOuNdArY";
"User-Agent" = "MixHR/0.0.1 (iPhone; iOS 7.0.4; Scale/2.00)";
} (null)

So why is body nil? I tried logging file, it is not empty.

回答1:

You try this code:

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSString *strURL = @"http://YOUR_IP:YOUR_PORT/YOUR_PATH/..";

    AFHTTPRequestOperationManager *manager     = [AFHTTPRequestOperationManager manager];
    AFJSONRequestSerializer *serializerRequest = [AFJSONRequestSerializer serializer];
    [serializerRequest setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

    AFJSONResponseSerializer *serializerResponse = [AFJSONResponseSerializer serializer];
    serializerResponse.readingOptions = NSJSONReadingAllowFragments;
    serializerResponse.acceptableContentTypes = [NSSet setWithObject:@"application/json"];

    manager.requestSerializer = serializerRequest;
    manager.responseSerializer = serializerResponse;

    UIImage *image = [UIImage imageNamed:@"image.png"];
    NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];

    NSDictionary *parameters = @{@"name":@"xxxx",
                                 @"surname":@"xxxx",
                                 };
    [manager POST:strURL parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFormData:imageData name:@"photo"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@""%@,operation.responseString);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@""%@,operation.responseString);
    }];
}