以一個(gè)頭像上傳為例子.
- 使用AFN上傳圖片
-
效果如下:
效果圖1
效果圖2
效果圖3
- 先給ViewController控制器添加一張圖片,添加點(diǎn)擊手勢(shì)
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
[_imageV addGestureRecognizer:tap];
_imageV.userInteractionEnabled = YES;
_imageV.layer.cornerRadius = 50;
_imageV.layer.masksToBounds = YES;
_imageV.image = [UIImage imageNamed:@"fire.jpg"];
- 手勢(shì)點(diǎn)擊的實(shí)現(xiàn)
-(void)tapAction{
UIActionSheet *action = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"退出" destructiveButtonTitle:nil otherButtonTitles:@"相機(jī)",@"相冊(cè)", nil];
// action.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
[action showInView:self.view];
}
- 設(shè)置代理,當(dāng)點(diǎn)擊actionsheet的時(shí)候,實(shí)現(xiàn)代理方法
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
// 設(shè)置代理
imagePickerController.delegate = self;
// 允許被編輯
imagePickerController.allowsEditing = YES;
self.imagePickerController = imagePickerController;
if (buttonIndex == 1) {
// 設(shè)置從圖庫(kù)里面選擇圖片
_imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:_imagePickerController animated:YES completion:nil];
}else if(buttonIndex == 0){
// 判斷是是否支持相機(jī)
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
// 設(shè)置從相機(jī)獲取圖片
_imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:_imagePickerController animated:YES completion:nil];
}else
{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"警告" message:@"請(qǐng)使用真機(jī)進(jìn)行測(cè)試" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alertView show];
NSLog(@"模擬其中無法打開照相機(jī),請(qǐng)?jiān)谡鏅C(jī)中使用");
}
}
}
- 點(diǎn)擊圖片后進(jìn)入代理方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
//UIImagePickerControllerCropRect // 編輯裁剪區(qū)域
//UIImagePickerControllerEditedImage // 編輯后的UIImage
//UIImagePickerControllerMediaType // 返回媒體的媒體類型
// UIImagePickerControllerOriginalImage // 原始的UIImage
//UIImagePickerControllerReferenceURL // 圖片地址
[self dismissViewControllerAnimated:YES completion:nil];
NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
if ([type isEqualToString:@"public.image"]) {
UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
// 將該圖片保存到本地
[self saveImage:image withName:@"avatar.png"];
NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"avatar.png"];
UIImage *saveImage = [[UIImage alloc] initWithContentsOfFile:fullPath];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// 設(shè)置時(shí)間格式
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *str = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
// 設(shè)置為頭像
self.imageV.image = saveImage;
// 上傳到服務(wù)器
NSDictionary *dict = @{
@"username":@"123456",
};
[self.manager POST:@"http://120.25.226.186:32812/upload" parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
//將圖片以表單形式上傳
/*
Data: 需要上傳的數(shù)據(jù)
name: 服務(wù)器參數(shù)的名稱
fileName: 文件在服務(wù)器上保存的名稱
mimeType: 文件的類型
*/
NSLog(@"%@",fullPath);
NSData *data1=[NSData dataWithContentsOfFile:fullPath];
[formData appendPartWithFileData:data1 name:@"file" fileName:fileName mimeType:@"image/png"];
} progress:^(NSProgress * _Nonnull uploadProgress) {
NSLog(@"%f",1.0 *uploadProgress.completedUnitCount/uploadProgress.totalUnitCount);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"成功---%@---%@",[responseObject class],responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"失敗---%@",error);
}];
}
}
-(void)saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
NSData *imageData = UIImageJPEGRepresentation(currentImage, 1); // 1為不縮放保存,取值為(0~1)
// 獲取沙河路徑
NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:imageName];
// 將照片寫入文件
[imageData writeToFile:fullPath atomically:YES];
}
}
完整的Demo地址.