ios上传图片


 1 //
 2 //  RequestPostUploadHelper.h
 3 //  demodes
 4 //
 5 //  Created by 张浩 on 13-5-8.
 6 //  Copyright (c) 2013年 张浩. All rights reserved.
 7 //
 8 
 9 #import <Foundation/Foundation.h>
10 
11 @interface RequestPostUploadHelper : NSObject
12 
13 /**
14  *POST 提交 并可以上传图片目前只支持单张
15  */
16 + (NSString *)postRequestWithURL: (NSString *)url  // IN
17                             postParems: (NSMutableDictionary *)postParems // IN 提交参数据集合
18                             picFilePath: (NSString *)picFilePath  // IN 上传图片路径
19                             picFileName: (NSString *)picFileName;  // IN 上传图片名称
20 
21 /**
22  * 修发图片大小
23  */
24 + (UIImage *) imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize) newSize;
25 /**
26  * 保存图片
27  */
28 + (NSString *)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName;
29 /**
30  * 生成GUID
31  */
32 + (NSString *)generateUuidString;
33 @end
  1 //
  2 //  RequestPostUploadHelper.m
  3 //  demodes
  4 //
  5 //  Created by 张浩 on 13-5-8.
  6 //  Copyright (c) 2013年 张浩. All rights reserved.
  7 //
  8 
  9 #import "RequestPostUploadHelper.h"
 10 
 11 @implementation RequestPostUploadHelper
 12 
 13 static NSString * const FORM_FLE_INPUT = @"file";
 14 
 15 + (NSString *)postRequestWithURL: (NSString *)url  // IN
 16                       postParems: (NSMutableDictionary *)postParems // IN
 17                      picFilePath: (NSString *)picFilePath  // IN
 18                      picFileName: (NSString *)picFileName;  // IN
 19 {
 20     
 21    
 22     NSString *TWITTERFON_FORM_BOUNDARY = @"0xKhTmLbOuNdArY";
 23     //根据url初始化request
 24     NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
 25                                                            cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
 26                                                        timeoutInterval:10];
 27     //分界线 --AaB03x
 28     NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
 29     //结束符 AaB03x--
 30     NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
 31     //得到图片的data
 32     NSData* data;
 33     if(picFilePath){
 34      
 35         UIImage *image=[UIImage imageWithContentsOfFile:picFilePath];
 36         //判断图片是不是png格式的文件
 37         if (UIImagePNGRepresentation(image)) {
 38             //返回为png图像。
 39             data = UIImagePNGRepresentation(image);
 40         }else {
 41             //返回为JPEG图像。
 42             data = UIImageJPEGRepresentation(image, 1.0);
 43         }
 44     }
 45     //http body的字符串
 46     NSMutableString *body=[[NSMutableString alloc]init];
 47     //参数的集合的所有key的集合
 48     NSArray *keys= [postParems allKeys];
 49     
 50     //遍历keys
 51     for(int i=0;i<[keys count];i++)
 52     {
 53         //得到当前key
 54         NSString *key=[keys objectAtIndex:i];
 55       
 56         //添加分界线,换行
 57         [body appendFormat:@"%@
",MPboundary];
 58         //添加字段名称,换2行
 59         [body appendFormat:@"Content-Disposition: form-data; name="%@"

",key];
 60         //添加字段的值
 61         [body appendFormat:@"%@
",[postParems objectForKey:key]];
 62         
 63          NSLog(@"添加字段的值==%@",[postParems objectForKey:key]);
 64     }
 65     
 66     if(picFilePath){
 67     ////添加分界线,换行
 68         [body appendFormat:@"%@
",MPboundary];
 69     
 70         //声明pic字段,文件名为boris.png
 71         [body appendFormat:@"Content-Disposition: form-data; name="%@"; filename="%@"
",FORM_FLE_INPUT,picFileName];
 72         //声明上传文件的格式
 73         [body appendFormat:@"Content-Type: image/jpge,image/gif, image/jpeg, image/pjpeg, image/pjpeg

"];
 74     }
 75     
 76     //声明结束符:--AaB03x--
 77     NSString *end=[[NSString alloc]initWithFormat:@"
%@",endMPboundary];
 78     //声明myRequestData,用来放入http body
 79     NSMutableData *myRequestData=[NSMutableData data];
 80 
 81     //将body字符串转化为UTF8格式的二进制
 82     [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
 83     if(picFilePath){
 84         //将image的data加入
 85         [myRequestData appendData:data];
 86     }
 87     //加入结束符--AaB03x--
 88     [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
 89   
 90     //设置HTTPHeader中Content-Type的值
 91     NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
 92     //设置HTTPHeader
 93     [request setValue:content forHTTPHeaderField:@"Content-Type"];
 94     //设置Content-Length
 95     [request setValue:[NSString stringWithFormat:@"%d", [myRequestData length]] forHTTPHeaderField:@"Content-Length"];
 96     //设置http body
 97     [request setHTTPBody:myRequestData];
 98     //http method
 99     [request setHTTPMethod:@"POST"];
100     
101     
102     NSHTTPURLResponse *urlResponese = nil;
103     NSError *error = [[NSError alloc]init];
104     NSData* resultData = [NSURLConnection sendSynchronousRequest:request   returningResponse:&urlResponese error:&error];
105     NSString* result= [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
106     if([urlResponese statusCode] >=200&&[urlResponese statusCode]<300){
107         NSLog(@"返回结果=====%@",result);
108         return result;
109     }
110     return nil;
111 }
112 
113 /**
114  * 修发图片大小
115  */
116 + (UIImage *) imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize) newSize{
117     newSize.height=image.size.height*(newSize.width/image.size.width);
118     UIGraphicsBeginImageContext(newSize);
119     [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
120     UIImage *newImage=UIGraphicsGetImageFromCurrentImageContext();
121     UIGraphicsEndImageContext();
122     return  newImage;
123 
124 }
125 
126 /**
127  * 保存图片
128  */
129 + (NSString *)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName{
130     NSData* imageData;
131     
132     //判断图片是不是png格式的文件
133     if (UIImagePNGRepresentation(tempImage)) {
134         //返回为png图像。
135         imageData = UIImagePNGRepresentation(tempImage);
136     }else {
137         //返回为JPEG图像。
138         imageData = UIImageJPEGRepresentation(tempImage, 1.0);
139     }   
140     NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
141     
142     NSString* documentsDirectory = [paths objectAtIndex:0];
143     
144     NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
145 
146     NSArray *nameAry=[fullPathToFile componentsSeparatedByString:@"/"];
147     NSLog(@"===fullPathToFile===%@",fullPathToFile);
148     NSLog(@"===FileName===%@",[nameAry objectAtIndex:[nameAry count]-1]);
149     
150     [imageData writeToFile:fullPathToFile atomically:NO];
151     return fullPathToFile;
152 }
153 
154 /**
155  * 生成GUID
156  */
157 + (NSString *)generateUuidString{
158     // create a new UUID which you own
159     CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
160     
161     // create a new CFStringRef (toll-free bridged to NSString)
162     // that you own
163     NSString *uuidString = (NSString *)CFUUIDCreateString(kCFAllocatorDefault, uuid);
164     
165     // transfer ownership of the string
166     // to the autorelease pool
167     [uuidString autorelease];
168     
169     // release the UUID
170     CFRelease(uuid);
171     
172     return uuidString;
173 }
174 @end

DEMO

 1 //
 2 //  UploadViewController.h
 3 //  demodes
 4 //
 5 //  Created by 张浩 on 13-5-6.
 6 //  Copyright (c) 2013年 张浩. All rights reserved.
 7 //
 8 
 9 #import <UIKit/UIKit.h>
10 
11 @interface UploadViewController : UIViewController<UIActionSheetDelegate,UIImagePickerControllerDelegate>
12 - (IBAction)onClickUploadPic:(id)sender;
13 - (void) snapImage;//拍照
14 - (void) pickImage;//从相册里找
15 - (UIImage *) imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize) newSize;
16 - (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName;
17 - (IBAction)onPostData:(id)sender;
18 - (NSString *)generateUuidString;
19 @end
  1 //
  2 //  UploadViewController.m
  3 //  demodes
  4 //
  5 //  Created by 张浩 on 13-5-6.
  6 //  Copyright (c) 2013年 张浩. All rights reserved.
  7 //
  8 
  9 #import "UploadViewController.h"
 10 #import "RequestPostUploadHelper.h"
 11 @interface UploadViewController ()
 12 
 13 @end
 14 
 15 NSString *TMP_UPLOAD_IMG_PATH=@"";
 16 @implementation UploadViewController
 17 
 18 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
 19 {
 20     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
 21     if (self) {
 22         // Custom initialization
 23     }
 24     return self;
 25 }
 26 
 27 - (void)viewDidLoad
 28 {
 29     [super viewDidLoad];
 30     // Do any additional setup after loading the view from its nib.
 31 }
 32 
 33 - (void)didReceiveMemoryWarning
 34 {
 35     [super didReceiveMemoryWarning];
 36     // Dispose of any resources that can be recreated.
 37 }
 38 
 39 - (IBAction)onClickUploadPic:(id)sender {
 40     UIActionSheet *menu=[[UIActionSheet alloc] initWithTitle:@"上传图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照上传",@"从相册上传", nil];
 41     menu.actionSheetStyle=UIActionSheetStyleBlackTranslucent;
 42     [menu showInView:self.view];
 43     
 44 }
 45 - (void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
 46      NSLog(@"33333333333333");
 47     if(buttonIndex==0){
 48         [self snapImage];
 49         NSLog(@"111111111111");
 50     }else if(buttonIndex==1){
 51         [self pickImage];
 52         NSLog(@"222222222222");
 53     }
 54     
 55     [actionSheet release];
 56 }
 57 //拍照
 58 - (void) snapImage{
 59     UIImagePickerController *ipc=[[UIImagePickerController alloc] init];
 60     ipc.sourceType=UIImagePickerControllerSourceTypeCamera;
 61     ipc.delegate=self;
 62     ipc.allowsEditing=NO;
 63     [self presentModalViewController:ipc animated:YES];
 64     
 65 }
 66 //从相册里找
 67 - (void) pickImage{
 68     UIImagePickerController *ipc=[[UIImagePickerController alloc] init];
 69     ipc.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
 70     ipc.delegate=self;
 71     ipc.allowsEditing=NO;
 72     [self presentModalViewController:ipc animated:YES];
 73 }
 74 
 75 -(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *) info{
 76     UIImage *img=[info objectForKey:@"UIImagePickerControllerOriginalImage"];
 77 
 78     if(picker.sourceType==UIImagePickerControllerSourceTypeCamera){
 79 //        UIImageWriteToSavedPhotosAlbum(img,nil,nil,nil);
 80     }
 81     UIImage *newImg=[self imageWithImageSimple:img scaledToSize:CGSizeMake(300, 300)];
 82     [self saveImage:newImg WithName:[NSString stringWithFormat:@"%@%@",[self generateUuidString],@".jpg"]];
 83     [self dismissModalViewControllerAnimated:YES];
 84     [picker release];
 85 
 86 }
 87 -(UIImage *) imageWithImageSimple:(UIImage*) image scaledToSize:(CGSize) newSize{
 88     newSize.height=image.size.height*(newSize.width/image.size.width);
 89     UIGraphicsBeginImageContext(newSize);
 90     [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
 91     UIImage *newImage=UIGraphicsGetImageFromCurrentImageContext();
 92     UIGraphicsEndImageContext();
 93     return  newImage;
 94 }
 95 
 96 - (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName
 97 
 98 {
 99     NSLog(@"===TMP_UPLOAD_IMG_PATH===%@",TMP_UPLOAD_IMG_PATH);
100     NSData* imageData = UIImagePNGRepresentation(tempImage);
101     
102     NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
103     
104     NSString* documentsDirectory = [paths objectAtIndex:0];
105     
106     // Now we get the full path to the file
107     
108     NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
109     
110     // and then we write it out
111     TMP_UPLOAD_IMG_PATH=fullPathToFile;
112     NSArray *nameAry=[TMP_UPLOAD_IMG_PATH componentsSeparatedByString:@"/"];
113     NSLog(@"===new fullPathToFile===%@",fullPathToFile);
114     NSLog(@"===new FileName===%@",[nameAry objectAtIndex:[nameAry count]-1]);
115     
116     [imageData writeToFile:fullPathToFile atomically:NO];
117     
118 }
119 
120 - (IBAction)onPostData:(id)sender {
121     NSMutableDictionary * dir=[NSMutableDictionary dictionaryWithCapacity:7];
122     //[dir setValue:@"save" forKey:@"m"];
123     [dir setValue:@"IOS上传试试" forKey:@"title"];
124     [dir setValue:@"IOS上传试试" forKey:@"content"];
125     [dir setValue:@"28" forKey:@"clubUserId"];
126     [dir setValue:@"1" forKey:@"clubSectionId"];
127     [dir setValue:@"192.168.0.26" forKey:@"ip"];
128     [dir setValue:@"asfdfasdfasdfasdfasdfasd=" forKey:@"sid"];
129     NSString *url=@"http://192.168.0.26:8090/api/club/topicadd.do?m=save";
130     NSLog(@"=======上传");
131     if([TMP_UPLOAD_IMG_PATH isEqualToString:@""]){
132         [RequestPostUploadHelper postRequestWithURL:url postParems:dir picFilePath:nil picFileName:nil];
133     }else{
134         NSLog(@"有图标上传");
135         NSArray *nameAry=[TMP_UPLOAD_IMG_PATH componentsSeparatedByString:@"/"];
136        [RequestPostUploadHelper postRequestWithURL:url postParems:dir picFilePath:TMP_UPLOAD_IMG_PATH picFileName:[nameAry objectAtIndex:[nameAry count]-1]];;
137     }
138  
139 }
140 - (NSString *)generateUuidString
141 {
142     // create a new UUID which you own
143     CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
144     
145     // create a new CFStringRef (toll-free bridged to NSString)
146     // that you own
147     NSString *uuidString = (NSString *)CFUUIDCreateString(kCFAllocatorDefault, uuid);
148     
149     // transfer ownership of the string
150     // to the autorelease pool
151     [uuidString autorelease];
152     
153     // release the UUID
154     CFRelease(uuid);
155     
156     return uuidString;
157 }
158 @end
原文地址:https://www.cnblogs.com/SangBigYe/p/3238230.html