首页 > 代码库 > iOS--AFNetWorking 上传图片到服务器
iOS--AFNetWorking 上传图片到服务器
//filePath 是要上传到服务器图片的路径,如果是截图图片,你可以image对象新建一个,来获取路径,比如已知一个UIImage对象image:
CGSize size=image.size;
NSData *DATA=http://www.mamicode.com/[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=http://www.mamicode.com/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 上传图片到服务器
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。