IOS上传照片(自己的代码整理了一下)

时间:2020-12-19 17:58:11

IOS上传照片源代码


UploadPhotoViewController.h 头文件


[html]  view plain copy
  1. #import <UIKit/UIKit.h>  
  2. #import "MBProgressHUD.h"  
  3. @interface UploadPhotoViewController :UIViewController<MBProgressHUDDelegate,UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>{  
  4.     MBProgressHUD *HUD;  
  5. }  
  6. -(void) snapImage;//拍照  
  7. -(void) pickImage;//从相册里找  
  8. - (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size;//把图缩放到合适的尽寸  
  9. @end  


UploadPhotoViewController.m 源文件

[html]  view plain copy
  1. #import "UploadPhotoViewController.h"  
  2. #import"ASIFormDataRequest.h"//ASIRequest用来上传图片  
  3. #import"HJManagedImageV.h"  //HJManagedImageV是图片缓存类,可以用其它异步加载图片类取代  
  4. #import "JSON.h"  
  5. #define UPLOAD_URL @"http://localhost/upload.php"//上传地址  
  6. @implementation UploadPhotoViewController  
  7.   
  8. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil  
  9. {  
  10.     self = [superinitWithNibName:nibNameOrNil bundle:nibBundleOrNil];  
  11.     if (self) {  
  12.         // Custom initialization  
  13.     }  
  14.     return self;  
  15. }  
  16.   
  17. - (void)didReceiveMemoryWarning  
  18. {  
  19.     // Releases the view if it doesn't have a superview.  
  20.     [superdidReceiveMemoryWarning];  
  21.       
  22.     // Release any cached data, images, etc that aren't in use.  
  23. }  
  24.   
  25. #pragma mark - View lifecycle  
  26.   
  27. - (void)viewDidLoad  
  28. {  
  29.     [superviewDidLoad];  
  30.     // Do any additional setup after loading the view from its nib.  
  31.     self.title =@"上代图片例子";  
  32. }  
  33.   
  34. - (void)viewWillAppear:(BOOL)animated  
  35. {  
  36.     [super viewWillAppear:animated];  
  37.       
  38.     HJManagedImageV* mi = [[[HJManagedImageValloc] initWithFrame:CGRectMake(20,20,280,280)]autorelease];  
  39.     mi.url = [NSURL URLWithString:@"图片地址"]];  
  40.     [mi showLoadingWheel];  
  41.     mi.tag = 777 ;  
  42.     [self.scrollView addSubview:mi];  
  43.     MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];  
  44.     [mi setCallbackOnImageTap:self method:@selector(uploadPortrait:)];//点击图片,执行上传图片操作  
  45.     [appDelegate.objMan manage:mi];//加载图片  
  46. }  
  47.   
  48. - (void)viewDidUnload  
  49. {  
  50.     [superviewDidUnload];  
  51.     // Release any retained subviews of the main view.  
  52.     // e.g. self.myOutlet = nil;  
  53. }  
  54.   
  55. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation  
  56. {  
  57.     // Return YES for supported orientations  
  58.     return (interfaceOrientation == UIInterfaceOrientationPortrait);  
  59. }  
  60.   
  61. - (void)dealloc {  
  62.     [super dealloc];  
  63. }  
  64.   
  65. //上传图片操作开始,选择图片的来源  
  66. -(void)uploadPortrait:(id)sender{  
  67.     UIActionSheet *menu = [[UIActionSheetalloc]  
  68.                            initWithTitle: @"更改图片"  
  69.                            delegate:self  
  70.                            cancelButtonTitle:@"取消"  
  71.                            destructiveButtonTitle:nil  
  72.                            otherButtonTitles:@"拍照",@"从相册上传",nil];  
  73.     menu.actionSheetStyle =UIActionSheetStyleBlackTranslucent;  
  74.     [menu showInView:self.navigationController.view];  
  75. }  
  76. - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex  
  77. {  
  78.     if(buttonIndex == 0){  
  79.          [self snapImage];  
  80.     }else if(buttonIndex ==1){  
  81.         [self pickImage];  
  82.     }  
  83.     [actionSheet release];  
  84. }  
  85.   
  86. - (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{    
  87.     // 创建一个bitmap的context    
  88.     // 并把它设置成为当前正在使用的context    
  89.     UIGraphicsBeginImageContext(size);    
  90.     // 绘制改变大小的图片    
  91.     [img drawInRect:CGRectMake(0,0, size.width, size.height)];    
  92.     // 从当前context中创建一个改变大小后的图片    
  93.     UIImage* scaledImage =UIGraphicsGetImageFromCurrentImageContext();    
  94.     // 使当前的context出堆栈    
  95.     UIGraphicsEndImageContext();    
  96.     //返回新的改变大小后的图片    
  97.     return scaledImage;    
  98. }  
  99. -(void)uploadPortraitTask:(NSDictionary *)info{  
  100.     // Do something usefull in here instead of sleeping ...  
  101.     NSURL *URL = [NSURLURLWithString:UPLOAD_URL];  
  102.     ASIFormDataRequest *Request = [ASIFormDataRequestrequestWithURL:URL];  
  103.     [Request setRequestMethod:@"POST"];    
  104.     [Request addRequestHeader:@"Content-Type"value:@"application/json"];  
  105.     [Request setTimeOutSeconds:60];  
  106.   
  107.     //[Request setPostValue:auth forKey:@"auth"];  
  108.     UIImage *img = [selfscaleToSize:[infoobjectForKey:@"UIImagePickerControllerOriginalImage"]size:CGSizeMake(300,300)];  
  109.     [Request setData:UIImagePNGRepresentation(img)forKey:@"file"];  
  110.       
  111.     [Request setDelegate:self];  
  112.     [Request setCompletionBlock:^{          
  113.         NSString *responseString = [Request responseString];  
  114.         //NSLog(@"Response: %@", responseString);  
  115.         NSDictionary *info = [responseString JSONValue];  
  116.         NSNumber *status = [info objectForKey:@"status"];  
  117.         if([status intValue]==1){  
  118.             HJManagedImageV* mi = (HJManagedImageV *)[self.viewviewWithTag:777];  
  119.             //set the URL that we want the managed image view to load  
  120.             [mi clear];  
  121.             mi.url = [NSURLURLWithString:[info objectForKey:@"filePath"]];  
  122.             [mi showLoadingWheel];  
  123.             mi.tag = 777 ;  
  124.             IBMEventAppDelegate *appDelegate = (IBMEventAppDelegate *)[[UIApplicationsharedApplication] delegate];  
  125.             //[mi setCallbackOnImageTap:self method:@selector(uploadPortrait:)];  
  126.             [appDelegate.objMan manage:mi];  
  127.             [appDelegate loadLoginInfoData];  
  128.             UIAlertView *av=[[[UIAlertViewalloc] initWithTitle:nilmessage:@"图片上传成功!" delegate:nilcancelButtonTitle:@"OK"otherButtonTitles:nil]autorelease];  
  129.             [av show];  
  130.               
  131.         }else if([statusintValue]==-1){  
  132.             UIAlertView *av=[[[UIAlertViewalloc] initWithTitle:nilmessage:[info objectForKey:@"msg"]delegate:nilcancelButtonTitle:@"OK"otherButtonTitles:nil]autorelease];  
  133.             [av show];  
  134.         }else{  
  135.             UIAlertView *av=[[[UIAlertViewalloc] initWithTitle:nilmessage:[info objectForKey:@"msg"]delegate:nilcancelButtonTitle:@"OK"otherButtonTitles:nil]autorelease];  
  136.             [av show];  
  137.         }  
  138.         [MBProgressHUDhideHUDForView:self.navigationController.viewanimated:YES];   
  139.     }];  
  140.     [Request setFailedBlock:^{  
  141.         NSError *error = [Request error];                                                                                             
  142.         NSLog(@"Error: %@,%@", error.localizedDescription,Request.url);  
  143.     }];  
  144.     [Request startSynchronous];  
  145. }  
  146. - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;   
  147. {  
  148. if (!error){  
  149.         UIAlertView *av=[[[UIAlertViewalloc] initWithTitle:nilmessage:@"Image written to photo album"delegate:nilcancelButtonTitle:@"OK"otherButtonTitles:nil]autorelease];  
  150.         [av show];  
  151.     }else{  
  152.         UIAlertView *av=[[[UIAlertViewalloc] initWithTitle:nilmessage:[NSStringstringWithFormat:@"Error writing to photo album: %@",[errorlocalizedDescription]] delegate:nilcancelButtonTitle:@"OK"otherButtonTitles:nil]autorelease];  
  153.         [av show];  
  154.     }  
  155.   
  156. }  
  157. - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info  
  158. {  
  159.     HUD = [MBProgressHUDshowHUDAddedTo:self.navigationController.viewanimated:YES];  
  160.     HUD.dimBackground =YES;  
  161.     HUD.delegate =self;  
  162.     HUD.labelText =@"请稍等";  
  163. HUD.square =YES;  
  164.     [HUDshowWhileExecuting:@selector(uploadPortraitTask:)onTarget:selfwithObject:info animated:YES];  
  165. //SETIMAGE([info objectForKey:@"UIImagePickerControllerOriginalImage"]);  
  166. [selfdismissModalViewControllerAnimated:YES];  
  167. [picker release];  
  168. }  
  169.   
  170. // Provide 2.x compliance  
  171. - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo  
  172. {  
  173. NSDictionary *dict = [NSDictionarydictionaryWithObject:imageforKey:@"UIImagePickerControllerOriginalImage"];  
  174. [selfimagePickerController:picker didFinishPickingMediaWithInfo:dict];  
  175. }  
  176.   
  177. // Optional but "expected" dismiss  
  178. /*  
  179.  - (void) imagePickerControllerDidCancel:   
  180.  (UIImagePickerController *)picker  
  181.  {  
  182.  [self dismissModalViewControllerAnimated:YES];  
  183.  [picker release];  
  184.  }  
  185.  */  
  186.   
  187. - (void) pickImage  
  188. {  
  189. UIImagePickerController *ipc = [[UIImagePickerControlleralloc] init];  
  190. ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;  
  191. ipc.delegate =self;  
  192. ipc.allowsEditing =NO;  
  193. [selfpresentModalViewController:ipc animated:YES];  
  194. }  
  195.   
  196. - (void) snapImage  
  197. {  
  198. UIImagePickerController *ipc = [[UIImagePickerControlleralloc] init];  
  199. ipc.sourceType = UIImagePickerControllerSourceTypeCamera;  
  200. ipc.delegate =self;  
  201. ipc.allowsEditing =NO;  
  202. [selfpresentModalViewController:ipc animated:YES];  
  203. }