iOS--AFNetWorking 上传图片到服务器
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS--AFNetWorking 上传图片到服务器相关的知识,希望对你有一定的参考价值。
//filePath 是要上传到服务器图片的路径,如果是截图图片,你可以image对象新建一个,来获取路径,比如已知一个UIImage对象image:
CGSize size=image.size;
NSData *DATA=[self imageWithImage:image scaledToSize:sise];
UIImage *image1=[UIImage imageWithData:DATA];
//图片保存的路径
NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
[fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:DATA attributes:nil];
NSString *filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath, @"/image.png"];
[self upload:filePath image:image1];
把方法中的yourURL 改成你自己的就可以用了,因为AFNetWorking 是异步的 所以我将后面分享功能的方法写在success里面的
- (void)upload:(NSString*)filePath image:(UIImage*)img
{
//表单请求,上传文件
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
manager.responseSerializer = [AFHTTPResponseSerializer serializer];//响应
manager.requestSerializer.timeoutInterval = 20;
[manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"textml",@"text/css",@"text/plain", @"application/javascript",@"application/json", @"application/x-www-form-urlencoded", nil]];
/* *这里需要特别注意一下,因为没有放具体的上传地址,所以这个上传方式是不成功的,但是方法是没错的,需要替换成正确的上传地址 */
NSDictionary *param=[NSDictionary dictionaryWithObjectsAndKeys:@"picture",@"paramName",filePath,@"file",nil];
[manager POST:@"yourURL" parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData)
{ //将图片以表单形式上传
NSData *data1=[NSData dataWithContentsOfFile:filePath];
NSData *imgData=UIImagePNGRepresentation(img);
[formData appendPartWithFileData:imgData name:@"picture" fileName:filePath mimeType:@"image/png"]; }
[formData appendPartWithFileData:imgData name:@"picture" fileName:filePath mimeType:@"image/png"]; }
progress:^(NSProgress *uploadProgress){ //进度 NSLog(@"进度%@",uploadProgress); }
success:^(NSURLSessionDataTask *task, id responseObject)
{
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
NSArray *keys= [dic allKeys];
//遍历keys
for(int i=0;i<[keys count];i++)
{
NSString *key=keys[i];
if([key isEqualToString:@"Data"])
{
NSString *url=[dic objectForKey:key];
url=[NSString stringWithFormat:@"http://123.207.238.220:81%@",url];
NSLog(@"%@",url);
[self share:url];
}
}
}
}
failure:^(NSURLSessionDataTask *task, NSError *error)
{ NSLog(@"%@",[error description]);
NSLog(@"%@",error); //因为没有有效地址,所以肯定是上传失败的,为了表现出效果,此处也替换为新头像
}]; }
以上是关于iOS--AFNetWorking 上传图片到服务器的主要内容,如果未能解决你的问题,请参考以下文章