我以为一直比较难弄,在网上查阅了一些资料,看的都比较懵,自己总结了一下。高手勿喷。
直接上代码
//创建属性
@property(nonatomic,strong)UIImagePickerController* pickerController;
@property(nonatomic,strong) UIImage * ownSendImage;
_pickerController是自创建的属性;
首先控制器遵循<UIImagePickerControllerDelegate,UINavigationControllerDelegate>这两个代理
- (void)viewDidLoad {
_pickerController= [[UIImagePickerControlleralloc]init];
_pickerController.delegate=self;
_pickerController.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
_pickerController.allowsEditing=YES;
}
//主要是在两个代理方法里面
#pragma mark-UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
ownSendImage= info[@"UIImagePickerControllerEditedImage"];
NSData* da =UIImageJPEGRepresentation(ownSendImage,0.4);
[self upLoadPictureWithData:da];
[self dismissViewControllerAnimated:YEScompletion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController*)picker{
[pickerdismissViewControllerAnimated:YEScompletion:^{
NSLog(@"取消");
}];
}
#pragma mark提交上传传入字典
- (void)upLoadPictureWithData:(NSData*)data{
NSMutableDictionary*dicde = [[NSMutableDictionaryalloc]init];
[dicde setObject:[database64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]forKey:@"file"];
//这里是你上传用的url及参数
NSString* url = [[NSStringstringWithFormat:@"http://www.xxxxx.com/csApi-img_upload-%@-%@.html",ID,terminalType]stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSetURLQueryAllowedCharacterSet]];
NSLog(@"上传url:%@",url);
[dicde setObject:data forKey:@"file"];
[dicde setObject:@"cae6a10963fce9bad62a10148a9be169" forKey:@"secret"];
[MBProgressHUDshowMessage:@"上传中..."view:self.view];
self.sessionManager= [AFHTTPSessionManagermanager];
self.sessionManager.responseSerializer= [AFHTTPResponseSerializerserializer];
self.sessionManager.responseSerializer.acceptableContentTypes= [NSSetsetWithObjects:@"application/json",@"text/json",@"text/plain",@"text/html",nil];
[self.sessionManagerPOST:urlparameters:dicdeconstructingBodyWithBlock:^(id_NonnullformData) {
[formData appendPartWithFileData:dataname:[NSString stringWithFormat:@"file"]fileName:@"image.jpg"mimeType:@"image/jpg"];
}progress:^(NSProgress*_NonnulluploadProgress) {
}success:^(NSURLSessionDataTask*_Nonnulltask,id_NullableresponseObject) {
NSDictionary* picDict = [NSJSONSerialization JSONObjectWithData:responseObjectoptions:NSJSONReadingMutableContainerserror:nil];
NSLog(@"图片上传:%@",picDict);
}failure:^(NSURLSessionDataTask*_Nullabletask,NSError*_Nonnullerror) {
NSLog(@"图片上传error:%@",error);
}];
}
网友评论