图片上传的思路实现
有很多情况下,App客户端需要上传图片到后台,我实现的一种方法是把图片转成base64位,上传到后台,后台返回保存图片的链接地址,然后把链接地址在上传到后台,多个图片时,就把得到的多个链接地址上传到后台,代码如下:
- (void)chooseImageWithIndex:(NSInteger)ind{ _imgIndex = ind; ChooseImgView *view = [LZ_NibViewHelper viewWithNibName:@"ChooseImgView"]; view.theWayChooseImg = ^(NSInteger index){ if(index==2) return; // act_flag=index; UIImagePickerControllerSourceType sourceType=UIImagePickerControllerSourceTypePhotoLibrary; if(index==0){//拍照 sourceType=UIImagePickerControllerSourceTypeCamera; if (![UIImagePickerController isSourceTypeAvailable:sourceType]){ kAlertMessage(@"检测到无效的摄像头设备"); return ; } } UIImagePickerController * picker = [[UIImagePickerController alloc]init]; picker.delegate = self; picker.allowsEditing=YES; picker.sourceType=sourceType; picker.modalTransitionStyle = UIModalTransitionStyleCoverVertical; [self presentViewController:picker animated:YES completion:nil]; }; [view showInTheView:self.view.window withCustomerType:self.customerType buttonndex:ind isQiye:0]; } -(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { [picker dismissViewControllerAnimated:YES completion:nil]; NSString* imme_type; if(picker.sourceType==UIImagePickerControllerSourceTypePhotoLibrary){ NSString *url; NSURL *imageurl; imageurl=[info objectForKey:UIImagePickerControllerReferenceURL]; url=[imageurl absoluteString]; NSRange range=[url rangeOfString:@"ext="]; imme_type =[[url substringFromIndex:range.location+4] lowercaseString]; if(![imme_type isEqualToString:@"png"] && ![imme_type isEqualToString:@"jpeg"] && ![imme_type isEqualToString:@"jpg"]){ kAlertMessage(@"图片非PNG、JPEG、JPG格式"); return; } } else imme_type=@"png"; UIImage* image = [info objectForKey:UIImagePickerControllerOriginalImage]; [self performSelector:@selector(selectPic:) withObject:image afterDelay:0.1]; } - (void)selectPic:(UIImage*)image{ [self uploading:image]; } #pragma mark-上传图片 -(void)uploading:(UIImage*)image1{ [self showLoading:YES AndText:@"请稍等"]; NSData *imageData = UIImageJPEGRepresentation(image1, 0.2); NSString *base64Image=[imageData base64Encoding]; NSDictionary * dic = @{ @"base64":base64Image }; [requestManager requestWebWithParaWithURL:url Parameter:dic Finish:^(NSDictionary *resultDic) {//请求成功 if ([resultDic objectForKey:@"data"]) { [self hideLoading];
//得到的图片地址预保存在字典中 [self.dataImgDict setObject:[resultDic objectForKey:@"data"] forKey:[NSString stringWithFormat:@"%ld",(long)_imgIndex + 1]]; } [self.tableView reloadData]; } Error:^(AFHTTPRequestOperation *operation, NSError *error, NSString *description) {//请求失败 [self showAllTextDialog:description]; [self hideLoading]; }]; }
多个图片上传就可以得到多个图片地址,再次上传图片地址就行了.