首页 > 代码库 > 纯代码上传图片的类--demo

纯代码上传图片的类--demo

镔哥哥就直接上代码了,上次一个朋友问我,能不能多点注释,我想对你说,看人代码主要是理解方法的演变,不懂就直接找度娘,并且我写的注释也不少啊。

注意:请不要直接负责代码,最好自己写一遍。

//

//  RequestPostUploadHelper.h

//  上传图片方法类

//

//  Created by apple on 14/12/13.

//  Copyright (c) 2014 huweibin. All rights reserved.

//


#import <Foundation/Foundation.h>

#import <UIKit/UIKit.h>

@interface RequestPostUploadHelper : NSObject

/**

 *POST 提交并可以上传图片目前只支持单张

 */

/*

 postParems提交参数据集合

 picFilePath上传图片路径

 picFileName上传图片名称

 */

+(NSString *)postRequestWithURL:(NSString *)url postParems:(NSMutableDictionary *)postParems picFilePath:(NSString *)picFilePath picFileName:(NSString *)picFileName;


/*

   图片大小

 */

+ (UIImage *) imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize) newSize;


/**

 * 保存图片

 */

+ (NSString *)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName;


/**

 * 生成GUID

 */

+ (NSString *)generateUuidStrin;

@end


//

//  RequestPostUploadHelper.m

//  上传图片方法类

//

//  Created by apple on 14/12/13.

//  Copyright (c) 2014 youdianshang. All rights reserved.

//


#import "RequestPostUploadHelper.h"


@implementation RequestPostUploadHelper



static NSString *const FORM_FLE_INPUT = @"file";


+(NSString *)postRequestWithURL:(NSString *)url postParems:(NSMutableDictionary *)postParems picFilePath:(NSString *)picFilePath picFileName:(NSString *)picFileName

{

    NSString * TWITTERFON_FORM_BOUNDARY = @"0xKhTmLbOuNdArY";

    

    //根据url初始化request

    NSMutableURLRequest* request = [NSMutableURLRequestrequestWithURL:[NSURLURLWithString:url]cachePolicy:NSURLRequestReloadIgnoringLocalCacheData

    timeoutInterval:10];

    //分界线 --AaB03x

    NSString *MPboundary=[[NSStringalloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];

    //结束符 AaB03x--

    NSString *endMPboundary=[[NSStringalloc]initWithFormat:@"%@--",MPboundary];

    //得到图片的data

    NSData* data;

    if(picFilePath){

        

        UIImage *image=[UIImageimageWithContentsOfFile:picFilePath];

        //判断图片是不是png格式的文件

        if (UIImagePNGRepresentation(image)) {

            //返回为png图像。

            data = http://www.mamicode.com/UIImagePNGRepresentation(image);

        }else {

            //返回为JPEG图像。

            data = http://www.mamicode.com/UIImageJPEGRepresentation(image,1.0);

        }

    }

    //http body的字符串

    NSMutableString *body=[[NSMutableStringalloc]init];

    //参数的集合的所有key的集合

    NSArray *keys= [postParems allKeys];

    

    //遍历keys

    for(int i=0;i<[keyscount];i++)

    {

        //得到当前key

        NSString *key=[keys objectAtIndex:i];

        

        //添加分界线,换行

        [body appendFormat:@"%@\r\n",MPboundary];

        //添加字段名称,换2

        [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];

        //添加字段的值

        [body appendFormat:@"%@\r\n",[postParemsobjectForKey:key]];

        

        NSLog(@"添加字段的值==%@",[postParemsobjectForKey:key]);

    }

    

    if(picFilePath){

        ////添加分界线,换行

        [body appendFormat:@"%@\r\n",MPboundary];

        

        //声明pic字段,文件名为boris.png

        [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n",FORM_FLE_INPUT,picFileName];

        //声明上传文件的格式

        [body appendFormat:@"Content-Type: image/jpge,image/gif, image/jpeg, image/pjpeg, image/pjpeg\r\n\r\n"];

    }

    

    //声明结束符:--AaB03x--

    NSString *end=[[NSStringalloc]initWithFormat:@"\r\n%@",endMPboundary];

    //声明myRequestData,用来放入http body

    NSMutableData *myRequestData=http://www.mamicode.com/[NSMutableDatadata];

    

    //body字符串转化为UTF8格式的二进制

    [myRequestData appendData:[bodydataUsingEncoding:NSUTF8StringEncoding]];

    if(picFilePath){

        //imagedata加入

        [myRequestData appendData:data];

    }

    //加入结束符--AaB03x--

    [myRequestData appendData:[enddataUsingEncoding:NSUTF8StringEncoding]];

    

    //设置HTTPHeaderContent-Type的值

    NSString *content=[[NSStringalloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];

    //设置HTTPHeader

    [request setValue:contentforHTTPHeaderField:@"Content-Type"];

    //设置Content-Length

    [request setValue:[NSStringstringWithFormat:@"%lu", (unsignedlong)[myRequestDatalength]] forHTTPHeaderField:@"Content-Length"];

    //设置http body

    [request setHTTPBody:myRequestData];

    //http method

    [request setHTTPMethod:@"POST"];

    

    

    NSHTTPURLResponse *urlResponese = nil;

    NSError *error = [[NSErroralloc]init];

    NSData* resultData = http://www.mamicode.com/[NSURLConnectionsendSynchronousRequest:request   returningResponse:&urlResponese error:&error];

    NSString* result= [[NSStringalloc] initWithData:resultDataencoding:NSUTF8StringEncoding];

    if([urlResponese statusCode] >=200&&[urlResponese statusCode]<300){

        NSLog(@"返回结果=====%@",result);

        return result;

    }

    return nil;


}


/**

 * 保存图片

 */

+ (NSString *)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName{

    NSData* imageData;

    

    //判断图片是不是png格式的文件

    if (UIImagePNGRepresentation(tempImage)) {

        //返回为png图像。

        imageData = http://www.mamicode.com/UIImagePNGRepresentation(tempImage);

    }else {

        //返回为JPEG图像。

        imageData = http://www.mamicode.com/UIImageJPEGRepresentation(tempImage,1.0);

    }

    NSArray* paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

    

    NSString* documentsDirectory = [paths objectAtIndex:0];

    

    NSString* fullPathToFile = [documentsDirectorystringByAppendingPathComponent:imageName];

    

    NSArray *nameAry=[fullPathToFile componentsSeparatedByString:@"/"];

    NSLog(@"===fullPathToFile===%@",fullPathToFile);

    NSLog(@"===FileName===%@",[nameAryobjectAtIndex:[nameAry count]-1]);

    

    [imageData writeToFile:fullPathToFile atomically:NO];

    return fullPathToFile;

}

/**

 * 生成GUID

 */

+ (NSString *)generateUuidString{

    // create a new UUID which you own

    CFUUIDRef uuid =CFUUIDCreate(kCFAllocatorDefault);

    

    // create a new CFStringRef (toll-free bridged to NSString)

    // that you own

    NSString *uuidString = (NSString *)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, uuid));

    

    // transfer ownership of the string

    // to the autorelease pool

    

    // release the UUID

    CFRelease(uuid);

    

    return uuidString;

}

@end

//

//  ViewController.h

//  上传图片方法类

//

//  Created by apple on 14/12/13.

//  Copyright (c) 2014 youdianshang. All rights reserved.

//


#import <UIKit/UIKit.h>


@interface ViewController :UIViewController<UIActionSheetDelegate,UIImagePickerControllerDelegate>


- (void)onClickUploadPic:(id)sender;

- (void) snapImage;//拍照

- (void) pickImage;//从相册里找

- (UIImage *) imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize) newSize;

- (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName;

- (void)onPostData:(id)sender;

- (NSString *)generateUuidString;

@end


//

//  ViewController.m

//  上传图片方法类

//

//  Created by apple on 14/12/13.

//  Copyright (c) 2014 huweibin. All rights reserved.

//


#import "ViewController.h"

#import "RequestPostUploadHelper.h"

@interface ViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>


@end

NSString *TMP_UPLOAD_IMG_PATH=@"";

@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    [selfonClickUploadPic];

    // Do any additional setup after loading the view, typically from a nib.

}


- (void)onClickUploadPic{

    UIActionSheet *menu=[[UIActionSheetalloc] initWithTitle:@"上传图片"delegate:selfcancelButtonTitle:@"取消"destructiveButtonTitle:nilotherButtonTitles:@"拍照上传",@"从相册上传",nil];

    menu.actionSheetStyle=UIActionSheetStyleBlackTranslucent;

    [menu showInView:self.view];

    

}


- (void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{

    NSLog(@"33333333333333");

    if(buttonIndex==0){

        [self snapImage];

        NSLog(@"111111111111");

    }else if(buttonIndex==1){

        [self pickImage];

        NSLog(@"222222222222");

    }

    


}

//拍照

- (void) snapImage{

    UIImagePickerController *ipc=[[UIImagePickerController alloc] init];

    ipc.sourceType=UIImagePickerControllerSourceTypeCamera;

    ipc.delegate=self;

    ipc.allowsEditing=NO;

    //[self presentModalViewController:ipc animated:YES];

    [self presentViewController:ipc animated:YES completion:nil];

    

}

//从相册里找

- (void) pickImage{

    UIImagePickerController *ipc=[[UIImagePickerController alloc] init];

    ipc.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;

    ipc.delegate=self;

    ipc.allowsEditing=NO;

    [self presentViewController:ipc animated:YES completion:nil];

}


-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *) info{

    UIImage *img=[info objectForKey:@"UIImagePickerControllerOriginalImage"];

    

    if(picker.sourceType==UIImagePickerControllerSourceTypeCamera){

        //        UIImageWriteToSavedPhotosAlbum(img,nil,nil,nil);

    }

    UIImage *newImg=[self imageWithImageSimple:img scaledToSize:CGSizeMake(300,300)];

    [self saveImage:newImg WithName:[NSString stringWithFormat:@"%@%@",[self generateUuidString],@".jpg"]];

    [self dismissViewControllerAnimated:YES completion:nil];

 

    

}

-(UIImage *) imageWithImageSimple:(UIImage*) image scaledToSize:(CGSize) newSize{

    newSize.height=image.size.height*(newSize.width/image.size.width);

    UIGraphicsBeginImageContext(newSize);

    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];

    UIImage *newImage=UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return  newImage;

}


- (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName


{

    NSLog(@"===TMP_UPLOAD_IMG_PATH===%@",TMP_UPLOAD_IMG_PATH);

    NSData* imageData = http://www.mamicode.com/UIImagePNGRepresentation(tempImage);

    

    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

    

    NSString* documentsDirectory = [paths objectAtIndex:0];

    

    // Now we get the full path to the file

    

    NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];

    

    // and then we write it out

    TMP_UPLOAD_IMG_PATH=fullPathToFile;

    NSArray *nameAry=[TMP_UPLOAD_IMG_PATH componentsSeparatedByString:@"/"];

    NSLog(@"===new fullPathToFile===%@",fullPathToFile);

    NSLog(@"===new FileName===%@",[nameAry objectAtIndex:[nameAry count]-1]);

    

    [imageData writeToFile:fullPathToFile atomically:NO];

    

}


- (void)onPostData:(id)sender {

    NSMutableDictionary * dir=[NSMutableDictionary dictionaryWithCapacity:7];

    //[dir setValue:@"save" forKey:@"m"];

    [dir setValue:@"IOS上传试试" forKey:@"title"];

    [dir setValue:@"IOS上传试试" forKey:@"content"];

    [dir setValue:@"28" forKey:@"clubUserId"];

    [dir setValue:@"1" forKey:@"clubSectionId"];

    [dir setValue:@"192.168.0.26" forKey:@"ip"];

    [dir setValue:@"asfdfasdfasdfasdfasdfasd=" forKey:@"sid"];

    NSString *url=@"http://192.168.0.26:8090/api/club/topicadd.do?m=save";

    NSLog(@"=======上传");

    if([TMP_UPLOAD_IMG_PATH isEqualToString:@""]){

        [RequestPostUploadHelper postRequestWithURL:url postParems:dir picFilePath:nil picFileName:nil];

    }else{

        NSLog(@"有图标上传");

        NSArray *nameAry=[TMP_UPLOAD_IMG_PATH componentsSeparatedByString:@"/"];

        [RequestPostUploadHelper postRequestWithURL:url postParems:dir picFilePath:TMP_UPLOAD_IMG_PATH picFileName:[nameAry objectAtIndex:[nameAry count]-1]];;

    }

    

}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end




纯代码上传图片的类--demo