我不知道这是不是一个错误,或者我只是做得不对。
这篇文章看起来非常接近为我解决,但没有:AFNetworking posts JSON arrays as multiple single-entry dictionaries
我尝试使用图片发送multipart / form-data POST并将字典(包含字典数组)传递给'参数'以JSON发送。
字典:
NSDictionary *parameters = @{@"photos" : @[@{@"photoID":@"0", @"imageURL":@"0", @"imageName":@"0"},
@{@"photoID":@"1", @"imageURL":@"1", @"imageName":@"1"},
@{@"photoID":@"2", @"imageURL":@"2", @"imageName":@"2"}]};
请求:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager POST:@"myURL" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:@"image" fileName:@"image" mimeType:@"image/png"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
正在发送和接收图像,但服务器上收到的JSON如下所示:
{
photos = (
{
imageName = 0;
},
{
imageURL = 0;
},
{
photoID = 0;
},
{
imageName = 1;
},
{
imageURL = 1;
},
{
photoID = 1;
},
{
imageName = 2;
},
{
imageURL = 2;
},
{
photoID = 2;
}
);
}
...多个单项词典的数组:(
而不是:
{
photos = (
{
imageName = 0;
imageURL = 0;
photoID = 0;
},
{
imageName = 1;
imageURL = 1;
photoID = 1;
},
{
imageName = 2;
imageURL = 2;
photoID = 2;
}
);
}
任何帮助都会很棒,谢谢!
答案 0 :(得分:2)
在form-data
中构建多部分请求时,参数将以AFNetworking
的形式发送。要在多部分响应中发送JSON
个编码实体,您需要将它们序列化并将它们附加到多部分响应中,作为服务器期望接收它们的方式。
根据服务器的期望,您可以使用以下内容:
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myJSON options:0 error:nil];
[formData appendPartWithFileData:jsonData name:@"name" fileName:nil mimeType:@"application/json"];
答案 1 :(得分:0)
如果您想要上传多张图片,并希望保持所有图片的参数名称相同,请执行以下操作:
NSDictionary *parameters = @{@"user_key": @"*****"};
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:queryStringss parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSError *error;
[formData appendPartWithFileData:imageData name:@"photo_file[0]" fileName:@"Picture44.png" mimeType:@"image/png"];
[formData appendPartWithFileData:imageData1 name:@"photo_file[1]" fileName:@"Picture45.png" mimeType:@"image/png"];
} error:nil];
通过这种方式,文件将作为数组发送到服务器。