我正在尝试使用AFNetworking 3.0将图像上传到服务器。
这是我的代码:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[[manager POST:setUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData)
{
//Current date with image name
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss a"];
[formData appendPartWithFileData:image name:namePara fileName:[NSString stringWithFormat:@"img_%@",[dateFormatter stringFromDate:[NSDate date]]] mimeType:@"image/png"];
}progress:nil
success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject)
{
NSLog(@"%@",responseObject);
[GMDCircleLoader hideFromView:self.view animated:YES];
NSMutableDictionary *dir = [[NSMutableDictionary alloc]initWithDictionary:responseObject];
if([dir valueForKey:@"error"])
{
UIAlertController *alert = [[singletone sharedManager]showAlert:NSLocalizedString(@"SIGNIN", nil) :[NSString stringWithFormat: @"%@",[dir valueForKey:@"error"]] ];
[self.parentViewController presentViewController:alert animated:YES completion:nil];
}
else
{
//Successfull
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"REGISTRATION", nil) message:[dir valueForKey:@"success"] preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * action)
{
[self.navigationController popViewControllerAnimated:YES];
}];
[alertController addAction:ok];
[self presentViewController:alertController animated:YES completion:nil];
}
NSLog(@"response object : %@",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"failure : %@",error.localizedDescription);
}]resume];
它将成功阻止错误:错误在图像上传。
我也尝试从Postman检查我的API响应,但它在Postman工作正常。这段代码有什么问题?
答案 0 :(得分:1)
尝试以下代码并使用AFNetworking 3.0:
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:BaseURL parameters:<parameter dictionary> constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
if (profile_pic.length!=0) {
[formData appendPartWithFileData:imageData name:@"profile_pic" fileName:@"ProfilePic" mimeType:@"image/jpeg"];
}
} error:nil];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error)
{
}
else
{
}
}];
[uploadTask resume];
答案 1 :(得分:0)
你试试这个
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
答案 2 :(得分:0)
NSData *nsdataFromBase64String = [[NSData alloc] initWithBase64EncodedString:imageBytes options:0];
NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:stringURL]];// Your API
[manager POST:stringURL parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
//do not put image inside parameters dictionary as I did, but append it!
[formData appendPartWithFileData:nsdataFromBase64String name:fIds fileName:fileN mimeType:@"image/jpeg"];
}
success:^(NSURLSessionDataTask *task, id responseObject)
{
imgRes=@"success";
//here is place for code executed in success case
}
failure:^(NSURLSessionDataTask *task, NSError *error)
{
imgRes=@"fail";
//here is place for code executed in error case
}];
在我的结尾完美运作
答案 3 :(得分:0)
您需要为@“Content-Type”将requestSerializer设置为@“multipart / form-data”。
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer=[AFJSONResponseSerializer serializer];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data"];
[manager.requestSerializer setValue:contentType forHTTPHeaderField:@"Content-Type"];
[manager POST:setUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss a"];
[formData appendPartWithFileData:image name:namePara fileName:[NSString stringWithFormat:@"img_%@",[dateFormatter stringFromDate:[NSDate date]]] mimeType:@"image/png"];
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"%@",responseObject);
[GMDCircleLoader hideFromView:self.view animated:YES];
NSMutableDictionary *dir = [[NSMutableDictionary alloc]initWithDictionary:responseObject];
if([dir valueForKey:@"error"])
{
UIAlertController *alert = [[singletone sharedManager]showAlert:NSLocalizedString(@"SIGNIN", nil) :[NSString stringWithFormat: @"%@",[dir valueForKey:@"error"]] ];
[self.parentViewController presentViewController:alert animated:YES completion:nil];
}
else
{
//Successfull
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"REGISTRATION", nil) message:[dir valueForKey:@"success"] preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * action)
{
[self.navigationController popViewControllerAnimated:YES];
}];
[alertController addAction:ok];
[self presentViewController:alertController animated:YES completion:nil];
}
NSLog(@"response object : %@",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"error: %@", error.localizedDescription);
}];
答案 4 :(得分:0)
NSData *nsdataFromBase64String = [[NSData alloc] initWithBase64EncodedString:"your image as base64 encoded" options:0];
NSDictionary *parameters = [NSMutableDictionary dictionary];
parameters = [NSDictionary dictionaryWithObjectsAndKeys:@"wr34", @"delivery_company_name", @"uname", @"user_name", @"123456789", @"contact_info", @"test1342@test.com", @"email",@"123456", @"password",@"SUV", @"car_type",@"White", @"car_color",@"GJ-1AE-2255", @"car_plate_no",@"43345dw", @"car_reg_no",@"123454", @"license_no",@"Model", @"car_model",@"location", @"location",@"4.3", @"latitude",@"8.7", @"longitude",@"notes", @"deliver_terms_conditions",@"notes", @"notes", nil];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:stringURL]];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager POST:stringURL parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
//do not put image inside parameters dictionary as I did, but append it!
[formData appendPartWithFileData:nsdataFromBase64String name:@"ToyotaSupra" fileName:@"ToyotaSupra" mimeType:@"image/png"];
}
success:^(NSURLSessionDataTask *task, id responseObject)
{
imgRes=@"success";
//here is place for code executed in success case
}
failure:^(NSURLSessionDataTask *task, NSError *error)
{
imgRes=@"fail";
//here is place for code executed in error case
}];
下载工作代码
https://www.dropbox.com/s/3ot6kpiqs3pn2h0/AFNetwork.zip?dl=0