使用json数据和afnetworking的multipart请求


request with json data and multipart using afnetworking

我使用的是AFNetworking 2.0,需要同时用json数据和多个图像构造到我的服务器的请求。

我可以想象的是,请求将采用以下结构:

Content-Type    multipart/form-data;boundary=abc
--abc
{"title":"Product discussion","attendee":[{"id":"1"},{"id":"2"},{"id":"3"},{"id":"4"},{"id":"5"}]}
--abc
Content-Disposition: form-data; name="img"
Content-Type: image/png
...image data...
--abc--

这里只是简化的结构。真正的会议数据更复杂,层次结构更多,所以我认为最好使用json。

然而,我不知道如何使用afnetworking(例如)来构建这样的数据结构

NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
[parameters setValue:meeting.title forKey:@"title"];
NSMutableArray *attendeeList = [[NSMutableArray alloc]init];
for(Attendee *attendee in meeting.attendeeList)
{
    NSMutableDictionary *attendeeDictionary = [[NSMutableDictionary alloc]init];
    [attendeeDictionary setValue:attendeeID forKey:@"id"];
    [attendeeList addObject: attendeeDictionary];
}
[parameters setValue:attendeeList forKey:@"attendee"];
httpClient.requestSerializer = [AFJSONRequestSerializer serializer];
[httpClient POST:@"createappointment.php" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    UIImage *image = [UIImage imageNamed:@"image.png"];
    NSData *imageData = UIImagePNGRepresentation(image);
    [formData appendPartWithFileData:imageData
                                    name:@"img"
                                fileName:@"img.png"
                                mimeType:@"image/png"];
    }
 } success:....

但该代码似乎忽略了AFJSONRequestSerializer,并将会议标题和与会者ID以POST数组的形式放置。

服务器端是PHP。通常,我可以从$_FILE获取图像,从php://input+json_decode,但在这种情况下,我不知道解析上述结构的最佳方式是什么?

有没有人也满足这样的要求,如何在iOS和服务器端正确解决?

因此,在这种情况下,您可以从$_POST而不是$_FILES获得它,或者您可以使用file_get_contents("php://input")