使用AFNetworking将图像与其他参数一起发送

时间:2013-05-22 12:43:10

标签: ios afnetworking

我正在更新使用ASIHTTPRequest AFNetworking的旧应用程序代码。就我而言,我正在向API发送一组数据,这些数据是不同的类型:图像和其他。

这是我到目前为止采用的代码,实现API客户端,请求共享实例,准备params字典并将其发送到远程API:

NSMutableDictionary *params = [NSMutableDictionary dictionary];
[params setValue:@"Some value" forKey:aKey];

[[APIClient sharedInstance]
 postPath:@"/post"
 parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
     //some logic


 } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
     //handle error

 }];

当我想要将图像添加到params字典时会出现什么情况?

使用ASIHTTPRequest,我曾经做过以下事情:

NSData *imgData = UIImagePNGRepresentation(anImage);

NSString *newStr = [anImageName stringByReplacingOccurrencesOfString:@"/"
                                                              withString:@"_"];



[request addData:imgData
    withFileName:[NSString stringWithFormat:@"%@.png",newStr]
  andContentType:@"image/png"
          forKey:anOtherKey];

我深入研究了AFNetworking文档,发现他们将图像附加到NSMutableRequest这样:

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
    [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
}];

我应该如何将这些图像数据整合到APIClient请求中?提前完成。

2 个答案:

答案 0 :(得分:20)

我使用相同的AFNetworking上传带有某些参数的图片。这段代码很适合我。可能会有所帮助

NSData *imageToUpload = UIImageJPEGRepresentation(uploadedImgView.image, 1.0);//(uploadedImgView.image);
if (imageToUpload)
{
    NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:keyParameter, @"keyName", nil];

    AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://------"]];

    NSMutableURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:@"API name as you have" parameters:parameters constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
        [formData appendPartWithFileData: imageToUpload name:@"image" fileName:@"temp.jpeg" mimeType:@"image/jpeg"];
    }];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSDictionary *jsons = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
         //NSLog(@"response: %@",jsons);

     }
                                     failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         if([operation.response statusCode] == 403)
         {
             //NSLog(@"Upload Failed");
             return;
         }
         //NSLog(@"error: %@", [operation error]);

     }];

    [operation start];
}

祝你好运!!

答案 1 :(得分:9)

使用AFNetworking 2.0.1,这段代码对我有用。

-(void) saveImage: (NSData *)imageData forImageName: (NSString *) imageName {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    NSString *imagePostUrl = [NSString stringWithFormat:@"%@/v1/image", BASE_URL];
    NSDictionary *parameters = @{@"imageName": imageName};

    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:imagePostUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageData name:@"image" fileName:imageName mimeType:@"image/jpeg"];
    }];

    AFHTTPRequestOperation *op = [manager HTTPRequestOperationWithRequest:request success: ^(AFHTTPRequestOperation *operation, id responseObject) {
        DLog(@"response: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        DLog(@"Error: %@", error);
    }];
    op.responseSerializer = [AFHTTPResponseSerializer serializer];
    [[NSOperationQueue mainQueue] addOperation:op];
}

如果需要JSON响应,请使用:

op.responseSerializer = [AFJSONResponseSerializer serializer];

而不是

op.responseSerializer = [AFHTTPResponseSerializer serializer];