使用 AFNetworking 上传图像
Posted
技术标签:
【中文标题】使用 AFNetworking 上传图像【英文标题】:Uploading images using AFNetworking 【发布时间】:2018-07-31 09:35:27 【问题描述】:我正在尝试使用 AFNetworking 库上传图片,它是一个发布请求,图片应该在正文中。我将它转换为 NSData 并尝试发送它,但它不起作用,我从后端人员那里得到的所有信息都是图像形式应该是图像文件。
我的代码如下:
+(void)imageUpload:(NSMutableDictionary *)imageData :(void(^)(BOOL success,NSError *error,NSString *path))block
NSString *urlString = [baseUrl stringByAppendingString:@"Media/ImageUpload"];
NSMutableDictionary *parameters = [NSMutableDictionary new];
[parameters setObject:[self getXsession] forKey:@"x-session"];
UIImage *image = [imageData objectForKey:@"image"];
NSData *imgData = UIImagePNGRepresentation(image);
NSMutableDictionary *bodyImage = [NSMutableDictionary new];
[bodyImage setObject:imgData forKey:@"image"];
[bodyImage setObject:@"leads_temp" forKey:@"folder"];
[self makePostRequestWithUrl:urlString parameters:parameters body:bodyImage headers:nil updateXsession:NO completionBlock:^(NSError *error, id responseObject)
BOOL success = [responseObject[@"meta"][@"status"]isEqualToString:@"OK"]?YES:NO;
if(success)
NSString *path = responseObject[@"response"][@"path"];
if (block)
block(success,nil,path);
else
if (block)
block(NO,error,nil);
];
发布请求:
+(void)makePostRequestWithUrl:(NSString *)url parameters:(NSMutableDictionary *)parameters body:(NSMutableDictionary*)body headers:(NSDictionary *)headers updateXsession:(BOOL)shouldUpdate completionBlock:(void(^)(NSError *error, id responseObject))block
NSError *error;
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:parameters error:&error];
request.timeoutInterval = 30;
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:body options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
stringWithFormat:@"%@\n%@\n%@",tableValue,jsonString,@""];
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error)
NSHTTPURLResponse *myResponse = (NSHTTPURLResponse *)response ;
if (myResponse && shouldUpdate)
//do some stuffs
if (block)
block(error, responseObject);
else
block(responseObject, error);
return ;
]resume];
知道解决方案是什么吗? 谢谢。
【问题讨论】:
我也有类似的问题:***.com/questions/40058781/… @Stefan 将UIImage
转换为UTF8 字符串不是一个好主意。可以分段上传UIImage
。
@Kuldeep 通过多部分它将是比特块(数据)。服务器期待图像而不是数据
@Stefan,根本没有块。
github.com/mikeho/QSUtilities/blob/master/QSStrings.h 我想有一个正当的理由为什么有一个完整的库作为将图像转换为 Bas64 的工具,或者这是一个很大的错误?
【参考方案1】:
试试这个。
-(void)uploadImage1:(UIImage *)img Dictionary:(NSMutableDictionary *)dictParam
NSData *imageData;
if (img == nil)
else
imageData = UIImageJPEGRepresentation(img, 0.7); // IF you want to compress image
AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
requestSerializer = [AFJSONRequestSerializer serializer];
responseSerializer = [AFJSONResponseSerializer serializer];
NSError *__autoreleasing* error = NULL;
NSMutableURLRequest *request = [requestSerializer multipartFormRequestWithMethod:@"POST" URLString:"YOUR_URL" parameters:dictParam constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
if (imageData != nil)
[formData appendPartWithFileData:imageData
name:@"profile_image" // Name of your Image Param
fileName:@"user_image.jpg"
mimeType:@"image/jpg"];
error:(NSError *__autoreleasing *)error];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.responseSerializer = responseSerializer;
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress)
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error)
if (error)
[SVProgressHUD dismiss];
NSLog(@"ERROR = %@",error.localizedDescription);
else
if ([[responseObject valueForKey:@"status"] intValue] == 1)
NSLog(@"SUCCESS");
else
NSLog(@"ERROR FROM SERVER = %@", [responseObject valueForKey:@"message"]);
];
[uploadTask resume];
【讨论】:
formData 是AFMultipartFormData
类型,它只是名称,您可以保留任何您想要的名称。
Refer this : github.com/AFNetworking/AFNetworking & search Upload Task 你会看到一个多部分请求的例子
@MrJ,欢迎您,也不要忘记投票。以上是关于使用 AFNetworking 上传图像的主要内容,如果未能解决你的问题,请参考以下文章