AF上传图片至服务器
一、从相册或者照相机获取头像上传服务器
1 #import "ViewController.h" 2 #import "AFNetworking.h" 3 #import "NSString+Hashing.h" 4 5 6 @interface ViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate> 7 { 8 UIImagePickerController *pickerController; 9 } 10 11 @property (weak, nonatomic) IBOutlet UIImageView *headImg; 12 13 14 @end 15 16 @implementation ViewController 17 18 - (void)viewDidLoad { 19 [super viewDidLoad]; 20 //初始化头像控件 21 [self initHeadIcon]; 22 //初始化pickController 23 [self createData]; 24 25 } 26 27 - (void)initHeadIcon 28 { 29 self.view.backgroundColor = [UIColor lightGrayColor]; 30 self.headImg.layer.cornerRadius = self.headImg.frame.size.height/2; 31 self.headImg.clipsToBounds = YES; 32 self.headImg.layer.borderColor = [UIColor whiteColor].CGColor; 33 self.headImg.layer.borderWidth = 3; 34 } 35 36 - (void)createData 37 { 38 //初始化pickerController 39 pickerController = [[UIImagePickerController alloc]init]; 40 pickerController.view.backgroundColor = [UIColor orangeColor]; 41 pickerController.delegate = self; 42 pickerController.allowsEditing = YES; 43 } 44 45 46 - (IBAction)tapAction:(UITapGestureRecognizer *)sender { 47 // if ([[[UIDevice currentDevice] systemVersion] intValue] < 8 ) { 48 // UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:@"选择头像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册",@"图库", nil]; 49 // [actionSheet showInView:[UIApplication sharedApplication].keyWindow]; 50 // }else{ 51 UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"选择头像" message:@"" preferredStyle:UIAlertControllerStyleActionSheet]; 52 53 UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { 54 55 }]; 56 57 UIAlertAction * cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { 58 59 if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) 60 { 61 NSLog(@"支持相机"); 62 [self makePhoto]; 63 }else{ 64 UIAlertController * aler = [UIAlertController alertControllerWithTitle:@"提示" message:@"请在设置-->隐私-->相机,中开启本应用的相机访问权限!!" preferredStyle:UIAlertControllerStyleAlert]; 65 66 UIAlertAction * okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { 67 68 }]; 69 70 UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { 71 72 }]; 73 74 [aler addAction:okAction]; 75 [aler addAction:cancelAction]; 76 [self presentViewController:aler animated:YES completion:nil]; 77 } 78 79 }]; 80 UIAlertAction * photoLibraryAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { 81 82 if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) 83 { 84 NSLog(@"支持相册"); 85 [self choosePicture]; 86 }else{ 87 // UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请在设置-->隐私-->照片,中开启本应用的相机访问权限!!" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"我知道了", nil]; 88 // [alert show]; 89 UIAlertController * aler = [UIAlertController alertControllerWithTitle:@"提示" message:@"请在设置-->隐私-->相机,中开启本应用的相机访问权限!!" preferredStyle:UIAlertControllerStyleAlert]; 90 UIAlertAction * okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { 91 92 }]; 93 UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { 94 95 }]; 96 97 [aler addAction:okAction]; 98 [aler addAction:cancelAction]; 99 100 [self presentViewController:aler animated:YES completion:nil]; 101 } 102 103 }]; 104 UIAlertAction * photosAlbumAction = [UIAlertAction actionWithTitle:@"图册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { 105 106 if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) 107 { 108 NSLog(@"支持图库"); 109 [self pictureLibrary]; 110 111 112 }else{ 113 UIAlertController * aler = [UIAlertController alertControllerWithTitle:@"提示" message:@"请在设置-->隐私-->相机,中开启本应用的相机访问权限!!" preferredStyle:UIAlertControllerStyleAlert]; 114 UIAlertAction * okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { 115 116 }]; 117 UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { 118 119 }]; 120 121 [aler addAction:okAction]; 122 [aler addAction:cancelAction]; 123 124 [self presentViewController:aler animated:YES completion:nil]; 125 } 126 127 }]; 128 129 [alertController addAction:cancelAction]; 130 [alertController addAction:cameraAction]; 131 [alertController addAction:photoLibraryAction]; 132 [alertController addAction:photosAlbumAction]; 133 134 [self presentViewController:alertController animated:YES completion:nil]; 135 136 // } 137 138 } 139 140 /* 141 - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex 142 { 143 if (buttonIndex == 0) {//相机 144 if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) 145 { 146 NSLog(@"支持相机"); 147 [self makePhoto]; 148 }else{ 149 UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请在设置-->隐私-->相机,中开启本应用的相机访问权限!!" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"我知道了", nil]; 150 [alert show]; 151 } 152 }else if (buttonIndex == 1){//相片 153 if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) 154 { 155 NSLog(@"支持相册"); 156 [self choosePicture]; 157 }else{ 158 UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请在设置-->隐私-->照片,中开启本应用的相机访问权限!!" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"我知道了", nil]; 159 [alert show]; 160 } 161 }else if (buttonIndex == 2){//图册 162 if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) 163 { 164 NSLog(@"支持图库"); 165 [self pictureLibrary]; 166 // [self presentViewController:picker animated:YES completion:nil]; 167 }else{ 168 UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请在设置-->隐私-->照片,中开启本应用的相机访问权限!!" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"我知道了", nil]; 169 [alert show]; 170 } 171 }else if (buttonIndex == 3){ 172 173 } 174 175 } 176 */ 177 178 //跳转到imagePicker里 179 - (void)makePhoto 180 { 181 pickerController.sourceType = UIImagePickerControllerSourceTypeCamera; 182 [self presentViewController:pickerController animated:YES completion:nil]; 183 } 184 185 //跳转到相册 186 - (void)choosePicture 187 { 188 pickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum; 189 [self presentViewController:pickerController animated:YES completion:nil]; 190 } 191 192 //跳转图库 193 - (void)pictureLibrary 194 { 195 pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; 196 [self presentViewController:pickerController animated:YES completion:nil]; 197 } 198 199 //用户取消退出picker时候调用 200 - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker 201 { 202 NSLog(@"%@",picker); 203 [pickerController dismissViewControllerAnimated:YES completion:^{ 204 205 }]; 206 } 207 208 //用户选中图片之后的回调 209 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info 210 { 211 212 NSLog(@"%s,info == %@",__func__,info); 213 214 UIImage *userImage = [self fixOrientation:[info objectForKey:@"UIImagePickerControllerOriginalImage"]]; 215 216 userImage = [self scaleImage:userImage toScale:0.3]; 217 218 //保存图片 219 // [self saveImage:userImage name:@"某个特定标示"]; 220 221 [pickerController dismissViewControllerAnimated:YES completion:^{ 222 223 224 }]; 225 [self.headImg setImage:userImage]; 226 self.headImg.contentMode = UIViewContentModeScaleAspectFill; 227 self.headImg.clipsToBounds = YES; 228 //照片上传 229 [self upDateHeadIcon:userImage]; 230 } 231 232 - (void)upDateHeadIcon:(UIImage *)photo{ 233 234 // NSData * data = UIImageJPEGRepresentation(photo, 0.5); 235 NSData * datapng = UIImagePNGRepresentation(photo); 236 237 NSString * url = @"http://ip/tony/upload_test.php"; 238 239 NSDictionary * parame = @{@"test":[NSString stringWithFormat:@"%@",datapng]}; 240 241 AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager]; 242 manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/x-www-form-urlencoded"]; 243 manager.requestSerializer = [AFHTTPRequestSerializer serializer]; 244 245 [manager POST:url parameters:parame constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 246 247 248 // NSString * path = [[NSBundle mainBundle] pathForResource:@"123" ofType:@"txt"]; 249 250 [formData appendPartWithFileData:datapng name:@"test" fileName:@"test" mimeType:@"image/png"]; 251 252 } success:^(AFHTTPRequestOperation *operation, id responseObject) { 253 254 NSLog(@"返回结果%@",responseObject); 255 256 } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 257 NSLog(@"请求失败%@",error.localizedDescription); 258 }]; 259 260 } 261 262 //修正照片方向(手机转90度方向拍照) 263 - (UIImage *)fixOrientation:(UIImage *)aImage { 264 265 // No-op if the orientation is already correct 266 if (aImage.imageOrientation == UIImageOrientationUp) 267 return aImage; 268 269 // We need to calculate the proper transformation to make the image upright. 270 // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored. 271 CGAffineTransform transform = CGAffineTransformIdentity; 272 273 switch (aImage.imageOrientation) { 274 case UIImageOrientationDown: 275 case UIImageOrientationDownMirrored: 276 transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height); 277 transform = CGAffineTransformRotate(transform, M_PI); 278 break; 279 280 case UIImageOrientationLeft: 281 case UIImageOrientationLeftMirrored: 282 transform = CGAffineTransformTranslate(transform, aImage.size.width, 0); 283 transform = CGAffineTransformRotate(transform, M_PI_2); 284 break; 285 286 case UIImageOrientationRight: 287 case UIImageOrientationRightMirrored: 288 transform = CGAffineTransformTranslate(transform, 0, aImage.size.height); 289 transform = CGAffineTransformRotate(transform, -M_PI_2); 290 break; 291 default: 292 break; 293 } 294 295 switch (aImage.imageOrientation) { 296 case UIImageOrientationUpMirrored: 297 case UIImageOrientationDownMirrored: 298 transform = CGAffineTransformTranslate(transform, aImage.size.width, 0); 299 transform = CGAffineTransformScale(transform, -1, 1); 300 break; 301 302 case UIImageOrientationLeftMirrored: 303 case UIImageOrientationRightMirrored: 304 transform = CGAffineTransformTranslate(transform, aImage.size.height, 0); 305 transform = CGAffineTransformScale(transform, -1, 1); 306 break; 307 default: 308 break; 309 } 310 311 // Now we draw the underlying CGImage into a new context, applying the transform 312 // calculated above. 313 CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height, 314 CGImageGetBitsPerComponent(aImage.CGImage), 0, 315 CGImageGetColorSpace(aImage.CGImage), 316 CGImageGetBitmapInfo(aImage.CGImage)); 317 CGContextConcatCTM(ctx, transform); 318 switch (aImage.imageOrientation) { 319 case UIImageOrientationLeft: 320 case UIImageOrientationLeftMirrored: 321 case UIImageOrientationRight: 322 case UIImageOrientationRightMirrored: 323 // Grr... 324 CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage); 325 break; 326 327 default: 328 CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage); 329 break; 330 } 331 332 // And now we just create a new UIImage from the drawing context 333 CGImageRef cgimg = CGBitmapContextCreateImage(ctx); 334 UIImage *img = [UIImage imageWithCGImage:cgimg]; 335 CGContextRelease(ctx); 336 CGImageRelease(cgimg); 337 return img; 338 } 339 340 //缩放图片 341 - (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize 342 { 343 UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize)); 344 [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)]; 345 UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext(); 346 UIGraphicsEndImageContext(); 347 NSLog(@"%@",NSStringFromCGSize(scaledImage.size)); 348 return scaledImage; 349 } 350 351 352 - (void)didReceiveMemoryWarning { 353 [super didReceiveMemoryWarning]; 354 355 } 356 357 @end
二、多张图片上传服务器
1 #import "ViewController.h" 2 #import "AFNetworking.h" 3 4 5 @interface ViewController () 6 7 @end 8 9 @implementation ViewController 10 11 - (void)viewDidLoad { 12 [super viewDidLoad]; 13 14 } 15 16 - (NSURLSessionUploadTask*)uploadTaskWithImage:(UIImage*)image completion:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionBlock { 17 18 NSData * imageData = UIImagePNGRepresentation(image); 19 20 // 构造 NSURLRequest 21 NSError* error = NULL; 22 NSDictionary * par = @{@"test":[NSString stringWithFormat:@"%@",imageData]}; 23 NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[self uploadUrl] parameters:par constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 24 25 [formData appendPartWithFileData:imageData name:@"test" fileName:@"test.png" mimeType:@"image/png"]; 26 27 } error:&error]; 28 29 // 可在此处配置验证信息 30 31 // 将 NSURLRequest 与 completionBlock 包装为 NSURLSessionUploadTask 32 AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; 33 34 NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) { 35 } completionHandler:completionBlock]; 36 37 return uploadTask; 38 } 39 40 /** 41 * 服务器上传图片接口 42 * 43 * @return 44 */ 45 - (NSString *)uploadUrl{ 46 return @"http://ip/tony/upload_test.php"; 47 } 48 49 /** 50 * 需上传的图片数组 51 * 52 * @return 53 */ 54 - (NSArray *)images{ 55 UIImage * image = [UIImage imageNamed:@"test.png"]; 56 UIImage * image1 = [UIImage imageNamed:@"11.png"]; 57 UIImage * image2 = [UIImage imageNamed:@"app.png"]; 58 59 return @[image,image1,image2]; 60 } 61 62 63 - (IBAction)runDispatchTest:(UIButton *)sender { 64 // 需要上传的数据 65 NSArray* images = [self images]; 66 67 // 准备保存结果的数组,元素个数与上传的图片个数相同,先用 NSNull 占位 68 NSMutableArray* result = [NSMutableArray array]; 69 for (UIImage* image in images) { 70 [result addObject:[NSNull null]]; 71 } 72 73 dispatch_group_t group = dispatch_group_create(); 74 75 for (NSInteger i = 0; i < images.count; i++) { 76 77 dispatch_group_enter(group); 78 79 //上传 80 NSURLSessionUploadTask* uploadTask = [self uploadTaskWithImage:images[i] completion:^(NSURLResponse *response, NSDictionary* responseObject, NSError *error) { 81 82 if (error) { 83 NSLog(@"第 %d 张图片上传失败: %@", (int)i + 1, error); 84 dispatch_group_leave(group); 85 } else { 86 NSLog(@"第 %d 张图片上传成功: %@", (int)i + 1, responseObject); 87 @synchronized (result) { // NSMutableArray 是线程不安全的,所以加个同步锁 88 if (responseObject) { 89 result[i] = responseObject; 90 } 91 } 92 dispatch_group_leave(group); 93 } 94 }]; 95 [uploadTask resume]; 96 } 97 98 dispatch_group_notify(group, dispatch_get_main_queue(), ^{ 99 NSLog(@"上传完成!"); 100 for (id response in result) { 101 NSLog(@"%@", response); 102 } 103 }); 104 } 105 106 107 108 - (void)didReceiveMemoryWarning { 109 [super didReceiveMemoryWarning]; 110 111 } 112 113 @end