我正在创建一个应用程序,我必须使用我从图库中获取的MultiPart(文件类型)上传图像。任何人都可以告诉我该怎么做。我如何传递该图像的参数。我搜索了很多,但没有找到任何解决方案。
我的代码如下: -
NSURL *baseUrl=[NSURL URLWithString:baseUrlStringForUserRegisterPage];
NSDictionary *parameters=@{@"pic":_imageViewUserSignUpView.image};
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer=[AFHTTPResponseSerializer serializer];
[manager POST:baseUrlStringForUserRegisterPage parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
}
progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
{
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
{
}];
baseUrlStringForUserRegisterPage带有我的URL。我在这里使用AFNetworking。
答案 0 :(得分:1)
这是它应该如何运作的:
NSURL *baseUrl = [NSURL URLWithString:baseUrlStringForUserRegisterPage];
// use parameters for other parameters than the images - if needed
// NSDictionary *parameters = @{};
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
// prepare your image(s)
UIImage *imageToUpload = _imageViewUserSignUpView.image;
NSData *imageData = UIImagePNGRepresentation(imageToUpload);
// NSData *imageData = UIImageJPEGRepresentation(imageToUpload, 0.75) // if you want to upload jpeg instead of png
[manager POST:baseUrlStringForUserRegisterPage parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:@"pic" fileName:@"pic.png" mimeType:@"image/png"];
// [formData appendPartWithFileData:imageData name:@"pic" fileName:@"pic.png" mimeType:@"image/jpeg"]; // if you want to upload jpeg instead of png
} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"success");
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"failure");
}];