xcode 使用 AFNetworking 上传多张图片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30182128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 07:07:34  来源:igfitidea点击:

Upload multiple images using AFNetworking

iosobjective-cswiftxcodeafnetworking

提问by Illep

I used the PickerControllerand loaded a few images on to a NSMutableArray.

我使用了PickerController并将一些图像加载到NSMutableArray.

Now i need to upload all of these images at once. am using AFNetworkingand how can i do this?

现在我需要一次上传所有这些图像。正在使用AFNetworking,我该怎么做?

I went through the AFNetworkingdocumentation and there was a section called Creating an Upload Task for a Multi-Part Request, with Progress. However, i am not able to upload the images that are in my NSMutableArray.

我浏览了AFNetworking文档,有一个名为Creating an Upload Task for a Multi-Part Request, with Progress. 但是,我无法上传我的NSMutableArray.

**** NB: I want to upload the images in the NSMutableArrayas a Byte Array. How can i do this? ****

**** 注意:我想以NSMutableArray字节数组的形式上传图像。我怎样才能做到这一点?****

The code i have so far,

我到目前为止的代码,

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

NSURL *URL = [NSURL URLWithString:@"site.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

回答by Hardik Mamtora

UIImage *image1 = [UIImage imageNamed:@"about_app"];
UIImage *image2 = [UIImage imageNamed:@"alter"];
NSArray *array = @[image1,image2];
NSMutableURLRequest *request = [[AFNetWorkSingleton shareInstance] multipartFormRequestWithMethod:@"POST" path:@"Mindex/getimg" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>formData){
int i = 0;
for(UIImage *eachImage in array)
{
    NSData *imageData = UIImageJPEGRepresentation(eachImage,0.5);
    [formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"file%d",i ] fileName:[NSString stringWithFormat:@"file%d.jpg",i ] mimeType:@"image/jpeg"];
    i++;
}
}];

Try this.

尝试这个。

回答by Urmi

-(void)uploadImages{

// image.finalImage - is image itself
// totalCount - Total number of images need to upload on server

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSDictionary *parameters = @{@"Key":@"Value",@"Key":@"Value"};
[manager POST:serverURL parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileData:UIImagePNGRepresentation(image.finalImage) name:@"ImageName" fileName:[[Helper getRandomString:8] stringByAppendingString:@".png"] mimeType:@"image/png"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:(NSData *)responseObject options:kNilOptions error:nil];
    _uploadCounter+=1;
    if(_uploadCounter<totalCount){
        [self uploadImages];
    }else {
        NSLog(@"Uploading all images done");
    }
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error");
}];

}

}

Try this, I have uploaded 10 images on server using this code and its successfully uploaded on sever.

试试这个,我已经使用此代码在服务器上上传了 10 张图片,并在服务器上成功上传。

回答by Ashish

If you want to upload multiple images and you want to keep the parameter name same for all the images you do it as below :

如果您想上传多张图片,并且希望所有图片的参数名称保持相同,请执行以下操作:

NSDictionary *parameters = @{@"user_key": @"*****"};
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:queryStringss parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    NSError *error;
    [formData appendPartWithFileData:imageData name:@"photo_file[0]" fileName:@"Picture44.png" mimeType:@"image/png"];
    [formData appendPartWithFileData:imageData1 name:@"photo_file[1]" fileName:@"Picture45.png" mimeType:@"image/png"];
} error:nil];

In this way the files would be sent as array to the server.

通过这种方式,文件将作为数组发送到服务器。

回答by Krunal


Alamofireis nice source/library for the same:


Alamofire是一个很好的源/库:

Swift 4:

斯威夫特 4:

Alamofire.upload(
    multipartFormData: { multipartFormData in
        multipartFormData.append(unicornImageURL, withName: "unicorn")
        multipartFormData.append(rainbowImageURL, withName: "rainbow")
    },
    to: "https://httpbin.org/post",
    encodingCompletion: { encodingResult in
        switch encodingResult {
        case .success(let upload, _, _):
            upload.responseJSON { response in
                debugPrint(response)
            }
        case .failure(let encodingError):
            print(encodingError)
        }
    }
)

回答by JoshA

Common technique for turning a UIImageinto NSData is with one of the following two methods.

将 aUIImage转换为 NSData 的常用技术是使用以下两种方法之一。

NSData *pngData = UIImagePNGRepresentation(myUIImage);
CGFloat quality = 1.0; // ranges from 0 to 1, 0% to 100%
NSData *jpgData = UIImageJPEGRepresentation(myUIImage, quality);

This of course assumes you know which type your image is. But since you used a PickerControllerto fetch the images, then it should be fairly easy to determine this. You just pull out the value under the key UIImagePickerControllerReferenceURLand check the extparameter. This comment shows it visually https://stackoverflow.com/a/11506499/1529638.

这当然假设您知道您的图像是哪种类型。但是由于您使用 aPickerController来获取图像,因此确定这一点应该相当容易。您只需将键下的值拉出UIImagePickerControllerReferenceURL并检查ext参数即可。此评论直观地显示了它https://stackoverflow.com/a/11506499/1529638