如同这个问题 https://stackoverflow.com/questions/20774692/afnetworking-multipart-request-body-is-nil.
使用 AFNetworking 2.0.3 并尝试使用 AFHTTPSessionManager 的 POST + ConstructionBodyWithBlock 上传图像。由于未知的原因,当向服务器发出请求时,HTTP 帖子正文似乎始终为空。
我在下面继承了 AFHTTPSessionManager (因此使用[self POST ...]
.
我尝试过以两种方式构建请求。
Method 1:我只是尝试传递参数,然后仅添加图像数据(如果存在)。
- (void) createNewAccount:(NSString *)nickname accountType:(NSInteger)accountType primaryPhoto:(UIImage *)primaryPhoto
{
NSString *accessToken = self.accessToken;
// Ensure none of the params are nil, otherwise it'll mess up our dictionary
if (!nickname) nickname = @"";
if (!accessToken) accessToken = @"";
NSDictionary *params = @{@"nickname": nickname,
@"type": [[NSNumber alloc] initWithInteger:accountType],
@"access_token": accessToken};
NSLog(@"Creating new account %@", params);
[self POST:@"accounts" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if (primaryPhoto) {
[formData appendPartWithFileData:UIImageJPEGRepresentation(primaryPhoto, 1.0)
name:@"primary_photo"
fileName:@"image.jpg"
mimeType:@"image/jpeg"];
}
} success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(@"Created new account successfully");
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"Error: couldn't create new account: %@", error);
}];
}
Method 2:尝试在块本身中构建表单数据:
- (void) createNewAccount:(NSString *)nickname accountType:(NSInteger)accountType primaryPhoto:(UIImage *)primaryPhoto
{
// Ensure none of the params are nil, otherwise it'll mess up our dictionary
if (!nickname) nickname = @"";
NSLog(@"Creating new account %@", params);
[self POST:@"accounts" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFormData:[nickname dataUsingEncoding:NSUTF8StringEncoding] name:@"nickname"];
[formData appendPartWithFormData:[NSData dataWithBytes:&accountType length:sizeof(accountType)] name:@"type"];
if (self.accessToken)
[formData appendPartWithFormData:[self.accessToken dataUsingEncoding:NSUTF8StringEncoding] name:@"access_token"];
if (primaryPhoto) {
[formData appendPartWithFileData:UIImageJPEGRepresentation(primaryPhoto, 1.0)
name:@"primary_photo"
fileName:@"image.jpg"
mimeType:@"image/jpeg"];
}
} success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(@"Created new account successfully");
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"Error: couldn't create new account: %@", error);
}];
}
无论使用哪种方法,当 HTTP 请求到达服务器时,都没有 POST 数据或查询字符串参数,只有 HTTP 标头。
Transfer-Encoding: Chunked
Content-Length:
User-Agent: MyApp/1.0 (iPhone Simulator; iOS 7.0.3; Scale/2.00)
Connection: keep-alive
Host: 127.0.0.1:5000
Accept: */*
Accept-Language: en;q=1, fr;q=0.9, de;q=0.8, zh-Hans;q=0.7, zh-Hant;q=0.6, ja;q=0.5
Content-Type: multipart/form-data; boundary=Boundary+0xAbCdEfGbOuNdArY
Accept-Encoding: gzip, deflate
有什么想法吗?还发布了一个错误AFNetworking 的 github 存储库 https://github.com/AFNetworking/AFNetworking/issues/1732.