ImageUploadViewController.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. // Do any additional setup after loading the view.
  89. }
  90. - (void)onBackClick:(UIButton *)sender {
  91. [self.navigationController popViewControllerAnimated:FALSE];
  92. }
  93. - (void)didReceiveMemoryWarning {
  94. [super didReceiveMemoryWarning];
  95. // Dispose of any resources that can be recreated.
  96. }
  97. - (IBAction)onClickAlbum:(id)sender {
  98. NSUInteger sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
  99. UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
  100. imagePickerController.delegate = self;
  101. imagePickerController.allowsEditing = YES;
  102. imagePickerController.sourceType = sourceType;
  103. [self presentViewController:imagePickerController animated:YES completion:^{}];
  104. }
  105. - (IBAction)onClickCamera:(id)sender {
  106. if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
  107. {
  108. return;
  109. }
  110. NSUInteger sourceType=UIImagePickerControllerSourceTypeCamera;
  111. UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
  112. imagePickerController.delegate = self;
  113. imagePickerController.allowsEditing = YES;
  114. imagePickerController.sourceType = sourceType;
  115. [self presentViewController:imagePickerController animated:YES completion:^{}];
  116. }
  117. - (IBAction)onClickUpload:(id)sender {
  118. if(self.dirty==false)
  119. {
  120. 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];
  121. // alert.
  122. [alert show];
  123. return;
  124. }
  125. self.uploadProgress.progress = 0;
  126. // UIAlertView * waitalert = [[UIAlertView alloc] initWithTitle:@"wait" message:@"uploading" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
  127. // [waitalert show];
  128. NSData *imageData = UIImagePNGRepresentation(self.imgview.image);
  129. AFHTTPRequestSerializer* serializer=[AFHTTPRequestSerializer serializer] ;
  130. NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
  131. AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  132. if(appDelegate.user!=nil)
  133. [params setValue:appDelegate.user forKey:@"user"];
  134. // if(appDelegate.contact_id!=nil)
  135. // [params setValue:appDelegate.contact_id forKey:@"contactId"];
  136. if(appDelegate.password!=nil)
  137. [params setValue:appDelegate.password forKey:@"password"];
  138. NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:@"POST" URLString:URL_UPLOAD_IMG parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  139. [formData appendPartWithFileData:imageData name:@"upfile" fileName:@"test.jpg" mimeType:@"image/png"];
  140. } error:nil];
  141. // NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:WEBSERVICE_URL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  142. // [formData appendPartWithFileData:imageData name:@"upfile" fileName:@"test" mimeType:@"image/png"];
  143. // } error:nil];
  144. //
  145. AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
  146. //manager.responseSerializer.acceptableContentTypes = [self.operationManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
  147. //
  148. NSProgress *progress = nil;
  149. NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
  150. // [progress removeObserver:self forKeyPath:@"fractionCompleted"];
  151. if (error) {
  152. NSString* err_msg = [error localizedDescription];
  153. NSLog(@"%@",err_msg);// [self.view updateWithMessage:[NSString stringWithFormat:@"Error : %@!", error.debugDescription]];
  154. NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  155. NSLog(@"data string: %@",str);
  156. [RAUtils message_alert:@"Can not connect to server please try again." title:@"Upload Image" controller:self] ;
  157. } else {
  158. NSLog(@"response ");
  159. NSData *data = [NSJSONSerialization dataWithJSONObject:(NSDictionary*)responseObject options:kNilOptions error:nil];
  160. // 再将NSData转为字符串
  161. NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  162. // NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  163. NSLog(@"data string: %@",jsonStr);
  164. NSDictionary* json = responseObject;
  165. if([[json valueForKey:@"result"] intValue]==2)
  166. {
  167. NSString* img_url_down = json[@"img_url_aname"];
  168. NSString* img_url_up = json[@"img_url"];
  169. if(self.returnValue)
  170. self.returnValue(img_url_down,img_url_up,self.imgview.image);
  171. [self.navigationController popViewControllerAnimated:false];
  172. }
  173. else
  174. {
  175. [RAUtils message_alert:[json valueForKey:@"err_msg"] title:@"Upload Image" controller:self] ;
  176. }
  177. }
  178. // [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  179. }];
  180. [self.uploadProgress setProgressWithUploadProgressOfTask:uploadTask animated:true];
  181. //
  182. [uploadTask resume];
  183. }
  184. #pragma mark - imagePicker delegate
  185. - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
  186. self.dirty = true;
  187. /*-------------------------------相机拍照--------------------------------------*/
  188. if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
  189. UIImage * image = [info objectForKey:UIImagePickerControllerEditedImage];
  190. image=[RAUtils img_compress:image kbsize:500];
  191. self.imgview.image = image;
  192. [picker dismissViewControllerAnimated:YES completion:^{
  193. }];
  194. } else if (picker .sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
  195. /**
  196. * UIImagePickerControllerEditedImage 取得的是被编辑过的图片,需要allowsEditing设置为YES
  197. * UIImagePickerControllerOriginalImage 取得的是相册中原始图片
  198. */
  199. UIImage * image = [info objectForKey:UIImagePickerControllerEditedImage];
  200. image=[RAUtils img_compress:image kbsize:500];
  201. self.imgview.image = image;
  202. [picker dismissViewControllerAnimated:YES completion:nil];
  203. }
  204. }
  205. - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
  206. [picker dismissViewControllerAnimated:YES completion:nil];
  207. // [picker presentViewController:cameraPicker animated:YES completion:nil];
  208. NSLog(@"%s",__FUNCTION__);
  209. }
  210. /*
  211. #pragma mark - Navigation
  212. // In a storyboard-based application, you will often want to do a little preparation before navigation
  213. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  214. // Get the new view controller using [segue destinationViewController].
  215. // Pass the selected object to the new view controller.
  216. }
  217. */
  218. @end