我知道它多次问过。但我面临一些问题,我想将多个图像发送到服务器。场景是,我使用自定义第三方库来选择多个图像。用户选择图像后,图像以数组形式出现。该阵列有两种类型,第一个数组带有用户选择的图像名称,无论他/她选择了多少图像,第二个是图像的文件路径数组,该数组包含数组路径。我有三个参数,而POST请求1st是图像名称数组来的名称,第二个是发送这些图像的id传递的ID,第三个是图像所在的图像。在我的代码中,我使用了AFHTTPRequestOperationManager,但我在标题上得到错误,这个类在我的项目中使用的AFNetworkk文件夹中没有头文件。我的代码就是这个,
-(void)Images{
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@"My URL"]];
int i=0;
for(UIImage *eachImage in _arrai)
{
NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed:@"mainImage"]);
[formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"file%d",i ] fileName:[NSString stringWithFormat:@"file%d.jpg",i ] mimeType:@"image/jpeg"];
i++;
}
NSDictionary *parameters = @{@"name":_arrainame, @"property_id" : Propid, @"image" : _arrai};
AFHTTPRequestOperation *op = [manager POST:@"mainImage" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//do not put image inside parameters dictionary as I did, but append it!
[formData appendPartWithFileData:imageData name:@"userfile" fileName:@"cat1.png" mimeType:@"image/png"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success: %@ ***** %@", operation.responseString, responseObject);
} failure:^(AFHTTPRequestOperation operation, NSError error) {
NSLog(@"Error: %@ ***** %@", operation.responseString, error);
}];
[op start];
}
答案 0 :(得分:0)
NSDictionary *parameters = @{@"name":_arrainame, @"property_id" : Propid};
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
int i=0;
for(NSString *eachImagePath in _arrai)
{
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:eachImagePath];
[formData appendPartWithFileURL:fileURL name:@"imageParamter" fileName:[NSString stringWithFormat:@"file%d.jpg",i ] mimeType:@"image/jpeg" error:nil];
i++;
}
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:nil
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"%@ %@", response, responseObject);
}
}];
[uploadTask resume];
试试这个