ImageUploadViewController.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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:UIImageRenderingModeAutomatic]
  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. AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  150. if(appDelegate.offline_mode)
  151. {
  152. }
  153. else
  154. {
  155. // UIAlertView * waitalert = [[UIAlertView alloc] initWithTitle:@"wait" message:@"uploading" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
  156. // [waitalert show];
  157. NSData *imageData = UIImagePNGRepresentation(self.imgview.image);
  158. AFHTTPRequestSerializer* serializer=[AFHTTPRequestSerializer serializer] ;
  159. NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
  160. if(appDelegate.user!=nil)
  161. [params setValue:appDelegate.user forKey:@"user"];
  162. // if(appDelegate.contact_id!=nil)
  163. // [params setValue:appDelegate.contact_id forKey:@"contactId"];
  164. if(appDelegate.password!=nil)
  165. [params setValue:appDelegate.password forKey:@"password"];
  166. NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:@"POST" URLString:URL_UPLOAD_IMG parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  167. [formData appendPartWithFileData:imageData name:@"upfile" fileName:@"test.jpg" mimeType:@"image/png"];
  168. } error:nil];
  169. // NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:WEBSERVICE_URL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  170. // [formData appendPartWithFileData:imageData name:@"upfile" fileName:@"test" mimeType:@"image/png"];
  171. // } error:nil];
  172. //
  173. AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
  174. //manager.responseSerializer.acceptableContentTypes = [self.operationManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
  175. //
  176. NSProgress *progress = nil;
  177. NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
  178. // [progress removeObserver:self forKeyPath:@"fractionCompleted"];
  179. if (error) {
  180. NSString* err_msg = [error localizedDescription];
  181. NSLog(@"%@",err_msg);// [self.view updateWithMessage:[NSString stringWithFormat:@"Error : %@!", error.debugDescription]];
  182. NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  183. NSLog(@"data string: %@",str);
  184. [RAUtils message_alert:@"Can not connect to server please try again." title:@"Upload Image" controller:self] ;
  185. } else {
  186. NSLog(@"response ");
  187. NSData *data = [NSJSONSerialization dataWithJSONObject:(NSDictionary*)responseObject options:kNilOptions error:nil];
  188. // 再将NSData转为字符串
  189. NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  190. // NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  191. NSLog(@"data string: %@",jsonStr);
  192. NSDictionary* json = responseObject;
  193. if([[json valueForKey:@"result"] intValue]==2)
  194. {
  195. NSString* img_url_down = json[@"img_url_aname"];
  196. NSString* img_url_up = json[@"img_url"];
  197. if(self.returnValue)
  198. self.returnValue(img_url_down,img_url_up,self.imgview.image);
  199. [self.navigationController popViewControllerAnimated:false];
  200. }
  201. else
  202. {
  203. [RAUtils message_alert:[json valueForKey:@"err_msg"] title:@"Upload Image" controller:self] ;
  204. }
  205. }
  206. // [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  207. }];
  208. [self.uploadProgress setProgressWithUploadProgressOfTask:uploadTask animated:true];
  209. //
  210. [uploadTask resume];
  211. }
  212. }
  213. #pragma mark - imagePicker delegate
  214. - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
  215. self.dirty = true;
  216. /*-------------------------------相机拍照--------------------------------------*/
  217. if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
  218. UIImage * image = [info objectForKey:UIImagePickerControllerEditedImage];
  219. image=[RAUtils img_compress:image kbsize:500];
  220. self.imgview.image = image;
  221. [picker dismissViewControllerAnimated:YES completion:^{
  222. }];
  223. } else if (picker .sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
  224. /**
  225. * UIImagePickerControllerEditedImage 取得的是被编辑过的图片,需要allowsEditing设置为YES
  226. * UIImagePickerControllerOriginalImage 取得的是相册中原始图片
  227. */
  228. UIImage * image = [info objectForKey:UIImagePickerControllerEditedImage];
  229. image=[RAUtils img_compress:image kbsize:500];
  230. self.imgview.image = image;
  231. [picker dismissViewControllerAnimated:YES completion:nil];
  232. }
  233. }
  234. - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
  235. [picker dismissViewControllerAnimated:YES completion:nil];
  236. // [picker presentViewController:cameraPicker animated:YES completion:nil];
  237. NSLog(@"%s",__FUNCTION__);
  238. }
  239. /*
  240. #pragma mark - Navigation
  241. // In a storyboard-based application, you will often want to do a little preparation before navigation
  242. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  243. // Get the new view controller using [segue destinationViewController].
  244. // Pass the selected object to the new view controller.
  245. }
  246. */
  247. @end