为每个AFMultipartFormData添加额外的参数

时间:2015-08-28 15:17:23

标签: ios objective-c afnetworking afnetworking-2

我想将一组图像发送到服务器,并且在阵列中的每个图像上我想将参数添加到调用中。我怎样才能做到这一点?我可以只将它添加到整个请求中。

     [self POST:@"api/sendimage"  parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageData
                                    name:@"files"
                                fileName:@"file_1" mimeType:@"image/jpeg"];
         [formData appendPartWithFileData:imageData
                                     name:@"files"
                                 fileName:@"file_2" mimeType:@"image/jpeg"];


        // etc.
    } success:[self successBlock:progressBackground] failure:[self failBlock:progressBackground]];

1 个答案:

答案 0 :(得分:0)

这是我项目的解决方案。你能试试吗?

  UIImage *img1 = [UIImage new];
  UIImage *img2 = [UIImage new];

  NSArray *photo = @[img1,img2]; 

  AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
  manager.requestSerializer = [AFJSONRequestSerializer serializer];

  NSString *path = @"api/sendimage";

  NSMutableDictionary *parameters;

  parameters = [@{
          @"Token" : @"123"
  } mutableCopy];

  [manager POST:path parameters:parameters constructingBodyWithBlock:^(id <AFMultipartFormData> formData) {

      if ( photo.count ) {
          [photo enumerateObjectsUsingBlock:^(UIImage *obj, NSUInteger idx, BOOL *stop) {

              NSData *imageData = UIImageJPEGRepresentation(obj,0.6);
              [formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"%i", arc4random() % 99999] fileName:[NSString stringWithFormat:@"%@.png", [NSString stringWithFormat:@"%i", arc4random() % 99999]] mimeType:@"image/jpeg"];

          }];

      }

  } success:^(AFHTTPRequestOperation *operation, id responseObject) {

      success();
  } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
      failure();
  }];