AFnetworking多部分请求正文为零

时间:2013-12-25 16:20:56

标签: ios multipart afnetworking-2

我正在尝试通过af 2.0多部分请求将图片上传到服务器,但似乎正文总是为空。以下是代码快照:

[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) {

}];

其中file是我从设备相机拍摄的照片并做了类似的事情

 NSData *file = UIImageJPEGRepresentation(avatar, 0.5)

然而,当我记录通过AF记录器发送的内容时,我会得到类似这样的内容

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)

那为什么身体没什么?我尝试记录文件,它不是空的。

1 个答案:

答案 0 :(得分:-1)

您尝试此代码:

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