使用AFNetworking上传多个图像或文件,

时间:2018-08-06 11:31:04

标签: ios objective-c afnetworking

我想使用AFNetworking上传多张图像。 像这样Please Check This Image

我附上了邮递员的例子。

我的代码:

NSString *key = [[mediaInfo allKeys] objectAtIndex:0];
NSDictionary *dict = [[mediaInfo objectForKey:key] objectAtIndex:0];
UIImage *image = [dict objectForKey:IQMediaImage];

NSMutableDictionary    *dictParam = [[NSMutableDictionary alloc] init];
[dictParam setValue:imageData forKey:@"Files"];

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:@BaseURL(@"/MediaUpload") parameters:dictParam progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {  }];

AFNetworking 3.0

2 个答案:

答案 0 :(得分:1)

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:@"multipart/form­data" forHTTPHeaderField:@"Content-Type"];

[manager POST:[NSString stringWithFormat:@"%@/api/1.0/customer/sign-up", DEFAULT_URL] parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

if (userHaveImage == YES) {
    [formData appendPartWithFileData:image name:@"img_profile" fileName:@"profileImage.jpg" mimeType:@"image/jpg"];
    [formData appendPartWithFormData:image name:@"img_profile"];
}

然后将图像转换为UTF8字符串并以该格式发送。

答案 1 :(得分:1)

AFURLSessionManager中检查此方法:

- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
                                     fromFile:(NSURL *)fileURL
                                     progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock
                            completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler

完整代码实现:

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *sessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

[[sessionManager uploadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@BaseURL(@"/MediaUpload")]]
                              fromFile:[NSURL fileURLWithPath:@"/path/to/uploading_file"]
                              progress:^(NSProgress * _Nonnull uploadProgress) { }
                     completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
}] resume];