ImageUploadViewController.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. //
  2. // ImageUploadViewController.m
  3. // RedAnt ERP Mobile
  4. //
  5. // Created by Ray on 11/4/15.
  6. // Copyright © 2015 United Software Applications, Inc. All rights reserved.
  7. //
  8. #import "ImageUploadViewController.h"
  9. #import "UIProgressView+AFNetworking.h"
  10. #import "AFHTTPSessionManager.h"
  11. #import "config.h"
  12. #import "RAUtils.h"
  13. #import "AppDelegate.h"
  14. //#import "UIAlertView+AFNetworking.h"
  15. #define TEST_URL @"http://192.168.1.3:8080/ios_server/ul.jsp"
  16. @interface ImageUploadViewController ()
  17. @end
  18. @implementation ImageUploadViewController
  19. -(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
  20. {
  21. UIApplication * app = [UIApplication sharedApplication];
  22. AppDelegate *appDelegate = (AppDelegate *)[app delegate];
  23. [appDelegate didRotated];
  24. // [CATransaction begin];
  25. // [CATransaction setAnimationDuration:0.5];
  26. // [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
  27. // // [self updatePreviewLayerForOrientation:toInterfaceOrientation];
  28. // _previewLayer.position = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
  29. //
  30. // // self.backgroundView.highLightRect = CGRectInset(self.focusZone.frame,6,6);
  31. // _previewLayer.bounds = rect;
  32. //
  33. // UIInterfaceOrientation orientation = [[UIApplication sharedApplication]statusBarOrientation];
  34. // switch (orientation) {
  35. //
  36. //
  37. //
  38. // case UIInterfaceOrientationPortrait:
  39. // // [_previewLayer setAffineTransform:CGAffineTransformMakeRotation(0)];
  40. //
  41. // _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationPortrait;
  42. // break;
  43. // case UIInterfaceOrientationPortraitUpsideDown:
  44. // //[_previewLayer setAffineTransform:CGAffineTransformMakeRotation(M_PI)];
  45. // _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationPortraitUpsideDown;
  46. // break;
  47. // case UIInterfaceOrientationLandscapeLeft:
  48. // // [_previewLayer setAffineTransform:CGAffineTransformMakeRotation(M_PI/2)];
  49. // _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationLandscapeLeft;
  50. // break;
  51. // case UIInterfaceOrientationLandscapeRight:
  52. // // [_previewLayer setAffineTransform:CGAffineTransformMakeRotation(-M_PI/2)];
  53. // _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationLandscapeRight;
  54. // break;
  55. // default:
  56. // break;
  57. // }
  58. // [CATransaction commit];
  59. NSTimeInterval animationDuration = 0.30f;
  60. [UIView beginAnimations:nil context:nil];
  61. [UIView setAnimationDuration:animationDuration];
  62. UIInterfaceOrientation orientation = [[UIApplication sharedApplication]statusBarOrientation];
  63. if (UIInterfaceOrientationIsLandscape(orientation))
  64. {
  65. self.buttonAlbum.frame = CGRectMake(942,120,48,48);
  66. self.buttonCamera.frame = CGRectMake(942,200,48,48);
  67. self.buttonUpload.frame = CGRectMake(942,363,48,48);
  68. // @property (strong, nonatomic) IBOutlet UIButton *buttonAlbum;
  69. // @property (strong, nonatomic) IBOutlet UIButton *buttonCamera;
  70. // @property (strong, nonatomic) IBOutlet UIButton *buttonUpload;
  71. }
  72. else
  73. {
  74. self.buttonAlbum.frame = CGRectMake(82,918,48,48);
  75. self.buttonCamera.frame = CGRectMake(173,918,48,48);
  76. self.buttonUpload.frame = CGRectMake(635,918,48,48);
  77. }
  78. [UIView commitAnimations];
  79. }
  80. - (void)viewDidLoad {
  81. [super viewDidLoad];
  82. UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
  83. style:UIBarButtonItemStylePlain
  84. target:self
  85. action:@selector( onBackClick:)];
  86. self.navigationItem.leftBarButtonItem = closeButton;
  87. self.imgview.image = self.img;
  88. UIApplication * app = [UIApplication sharedApplication];
  89. AppDelegate *appDelegate = (AppDelegate *)[app delegate];
  90. // [appDelegate didRotated];
  91. NSTimeInterval animationDuration = 0.30f;
  92. [UIView beginAnimations:nil context:nil];
  93. [UIView setAnimationDuration:animationDuration];
  94. UIInterfaceOrientation orientation = [[UIApplication sharedApplication]statusBarOrientation];
  95. if (UIInterfaceOrientationIsLandscape(orientation))
  96. {
  97. self.buttonAlbum.frame = CGRectMake(942,120,48,48);
  98. self.buttonCamera.frame = CGRectMake(942,200,48,48);
  99. self.buttonUpload.frame = CGRectMake(942,363,48,48);
  100. // @property (strong, nonatomic) IBOutlet UIButton *buttonAlbum;
  101. // @property (strong, nonatomic) IBOutlet UIButton *buttonCamera;
  102. // @property (strong, nonatomic) IBOutlet UIButton *buttonUpload;
  103. }
  104. else
  105. {
  106. self.buttonAlbum.frame = CGRectMake(82,918,48,48);
  107. self.buttonCamera.frame = CGRectMake(173,918,48,48);
  108. self.buttonUpload.frame = CGRectMake(635,918,48,48);
  109. }
  110. [UIView commitAnimations];
  111. // Do any additional setup after loading the view.
  112. }
  113. - (void)onBackClick:(UIButton *)sender {
  114. [self.navigationController popViewControllerAnimated:FALSE];
  115. }
  116. - (void)didReceiveMemoryWarning {
  117. [super didReceiveMemoryWarning];
  118. // Dispose of any resources that can be recreated.
  119. }
  120. - (IBAction)onClickAlbum:(id)sender {
  121. NSUInteger sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
  122. UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
  123. imagePickerController.delegate = self;
  124. imagePickerController.allowsEditing = YES;
  125. imagePickerController.sourceType = sourceType;
  126. [self presentViewController:imagePickerController animated:YES completion:^{}];
  127. }
  128. - (IBAction)onClickCamera:(id)sender {
  129. if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
  130. {
  131. return;
  132. }
  133. NSUInteger sourceType=UIImagePickerControllerSourceTypeCamera;
  134. UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
  135. imagePickerController.delegate = self;
  136. imagePickerController.allowsEditing = YES;
  137. imagePickerController.sourceType = sourceType;
  138. [self presentViewController:imagePickerController animated:YES completion:^{}];
  139. }
  140. - (IBAction)onClickUpload:(id)sender {
  141. if(self.dirty==false)
  142. {
  143. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Upload", nil) message:NSLocalizedString(@"Please set a photo first.", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"Ok", nil) otherButtonTitles:nil, nil];
  144. // alert.
  145. [alert show];
  146. return;
  147. }
  148. self.uploadProgress.progress = 0;
  149. // UIAlertView * waitalert = [[UIAlertView alloc] initWithTitle:@"wait" message:@"uploading" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
  150. // [waitalert show];
  151. NSData *imageData = UIImagePNGRepresentation(self.imgview.image);
  152. AFHTTPRequestSerializer* serializer=[AFHTTPRequestSerializer serializer] ;
  153. NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
  154. AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  155. if(appDelegate.user!=nil)
  156. [params setValue:appDelegate.user forKey:@"user"];
  157. // if(appDelegate.contact_id!=nil)
  158. // [params setValue:appDelegate.contact_id forKey:@"contactId"];
  159. if(appDelegate.password!=nil)
  160. [params setValue:appDelegate.password forKey:@"password"];
  161. NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:@"POST" URLString:URL_UPLOAD_IMG parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  162. [formData appendPartWithFileData:imageData name:@"upfile" fileName:@"test.jpg" mimeType:@"image/png"];
  163. } error:nil];
  164. // NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:WEBSERVICE_URL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  165. // [formData appendPartWithFileData:imageData name:@"upfile" fileName:@"test" mimeType:@"image/png"];
  166. // } error:nil];
  167. //
  168. AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
  169. //manager.responseSerializer.acceptableContentTypes = [self.operationManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
  170. //
  171. NSProgress *progress = nil;
  172. NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
  173. // [progress removeObserver:self forKeyPath:@"fractionCompleted"];
  174. if (error) {
  175. NSString* err_msg = [error localizedDescription];
  176. NSLog(@"%@",err_msg);// [self.view updateWithMessage:[NSString stringWithFormat:@"Error : %@!", error.debugDescription]];
  177. NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  178. NSLog(@"data string: %@",str);
  179. [RAUtils message_alert:@"Can not connect to server please try again." title:@"Upload Image" controller:self] ;
  180. } else {
  181. NSLog(@"response ");
  182. NSData *data = [NSJSONSerialization dataWithJSONObject:(NSDictionary*)responseObject options:kNilOptions error:nil];
  183. // 再将NSData转为字符串
  184. NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  185. // NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  186. NSLog(@"data string: %@",jsonStr);
  187. NSDictionary* json = responseObject;
  188. if([[json valueForKey:@"result"] intValue]==2)
  189. {
  190. NSString* img_url_down = json[@"img_url_aname"];
  191. NSString* img_url_up = json[@"img_url"];
  192. if(self.returnValue)
  193. self.returnValue(img_url_down,img_url_up,self.imgview.image);
  194. [self.navigationController popViewControllerAnimated:false];
  195. }
  196. else
  197. {
  198. [RAUtils message_alert:[json valueForKey:@"err_msg"] title:@"Upload Image" controller:self] ;
  199. }
  200. }
  201. // [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  202. }];
  203. [self.uploadProgress setProgressWithUploadProgressOfTask:uploadTask animated:true];
  204. //
  205. [uploadTask resume];
  206. }
  207. #pragma mark - imagePicker delegate
  208. - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
  209. self.dirty = true;
  210. /*-------------------------------相机拍照--------------------------------------*/
  211. if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
  212. UIImage * image = [info objectForKey:UIImagePickerControllerEditedImage];
  213. image=[RAUtils img_compress:image kbsize:500];
  214. self.imgview.image = image;
  215. [picker dismissViewControllerAnimated:YES completion:^{
  216. }];
  217. } else if (picker .sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
  218. /**
  219. * UIImagePickerControllerEditedImage 取得的是被编辑过的图片,需要allowsEditing设置为YES
  220. * UIImagePickerControllerOriginalImage 取得的是相册中原始图片
  221. */
  222. UIImage * image = [info objectForKey:UIImagePickerControllerEditedImage];
  223. image=[RAUtils img_compress:image kbsize:500];
  224. self.imgview.image = image;
  225. [picker dismissViewControllerAnimated:YES completion:nil];
  226. }
  227. }
  228. - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
  229. [picker dismissViewControllerAnimated:YES completion:nil];
  230. // [picker presentViewController:cameraPicker animated:YES completion:nil];
  231. NSLog(@"%s",__FUNCTION__);
  232. }
  233. /*
  234. #pragma mark - Navigation
  235. // In a storyboard-based application, you will often want to do a little preparation before navigation
  236. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  237. // Get the new view controller using [segue destinationViewController].
  238. // Pass the selected object to the new view controller.
  239. }
  240. */
  241. @end