iOS开发中,经常需要我们上传图片到服务器,直接上代码。
#import "ViewController.h"
#import "AFNetworking.h"
/**
* 遵守UIImagePickerControllerDelegate代理方法
*/
@interface ViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)postImg:(UIButton *)sender
{
UIActionSheet * actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消 " destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"选取照片", nil];
/**
* 设置actinsheet的样式
*/
[actionSheet setActionSheetStyle:UIActionSheetStyleDefault];
/**
* 显示actionsheet
*/
[actionSheet showInView:self.view];
}
#pragma mark -- UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
switch (buttonIndex) {
case 0:
{
/**
* 打开照相机,先判断相机能不能打开,isSourceTypeAvailable后面是三个枚举值。UIImagePickerControllerSourceTypeCamera表示相机可用。
*/
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
/**
* picker.delegate 有两个,UINavigationControllerDelegate和UIImagePickerControllerDelegate
*/
picker.delegate = self;
/**
* 设置拍照之后是否可编辑,如果设置成可编辑的话会在代理方法返回的字典里面多一些键值。
*/
picker.allowsEditing = YES;
/**
* 调用系统相机,UIImagePickerControllerSourceTypeCamera表示调用相机。UIImagePickerControllerSourceTypePhotoLibrary表示照片库
*/
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self.navigationController presentViewController:picker animated:YES completion:nil];
}else{
/**
* 否则,相机不可用。
*/
UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"没有摄像头" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alert show];
}
}
break;
case 1:
{
/**
* 打开图片库。先判断照片库是否可用
*/
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
/**
* 和前面设置一样
*/
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:nil];
}else{
/**
* 否则,图片库不能用。
*/
UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"图片库不可用" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alert show];
}
}
break;
default:
break;
}
}
#pragma mark -- UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
/**
* 点击选择时,会触发此方法。图片所有的信息,都包含在info中,可以打印看一下。打印可以看出,图片的key值是UIImagePickerControllerEditedImage
*/
UIImage * img = [info objectForKey:UIImagePickerControllerEditedImage];
/**
* PS:此时UIImagePickerControllerEditedImage是一个宏,所以[info objectForKey:UIImagePickerControllerEditedImage]和[info objectForKey:@"UIImagePickerControllerEditedImage"]是等价的。
*/
/**
* 如果图片是拍照得来的,那么要存入图片库。
*/
if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
UIImageWriteToSavedPhotosAlbum(img, nil, nil, nil);//把图片存到图片库
}
/**
* 把图片转坏二进制图片,因为不知道是ipg格式还是png格式,所以要进行判断。
*/
NSData * data;
if (UIImagePNGRepresentation(img) == nil) {
/**
* 把图片转化为二进制
*
* @param img 图片
* @param compressionQuality#> 图片的质量,可填0到1之间的数,1的质量最好 description#>
*
* @return 返回二进制数据
*/
data = UIImageJPEGRepresentation(img, 1);//如果png转化为二进制为0,则图片肯定是jpg格式的。
}else{
data = UIImagePNGRepresentation(img);
}
/**
* 如果需要把图片存入沙河,则执行下面的操作
*/
/**
* ///
*/
/**
* 获取Documents路径
*/
NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
/**
* 创建文件管理器
*/
NSFileManager *fileManager = [NSFileManager defaultManager];
/**
* 把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
*/
[fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
/**
* 下面这一句的意思是先把Documents/image.png路径下的文件删除,
*/
[fileManager removeItemAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] error:nil];
[fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data attributes:nil];
/**
*
*/
/**
* 获取到图片,然后上传。
*/
/**
* 上传之前先将图片转化成base64,作为一个参数,看后台需要什么参数。
*/
NSString * imgStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
NSMutableDictionary * parameters = [NSMutableDictionary dictionary];
[manager POST:@"后台接口" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
/**
* appendPartWithFileData : 上传的二进制数据
* name : 服务器存放图片的文件路径
* fileName : 上传后文件的名字。
* mimeType : 文件类型,图片就是@"image/jpg" ;
这几个参数不绝对,看后台怎么做接口。
*/
[formData appendPartWithFileData:data name:@"" fileName:@"" mimeType:@""];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"成功");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"失败");
}];
}
如有不对的地方,还请批评指正。