iOS Upload Image Method class

Source: Internet
Author: User

iphone development encountered uploading picture problems, find more information, finally encapsulated a class, please point out the code as follows
  requestpostuploadhelper.h//  demodes////  Created by Zhang Hao on 13-5-8.//  Copyright (c) 2013 Zhang Hao. All rights reserved.//#import <Foundation/Foundation.h> @interface requestpostuploadhelper:nsobject/** *post Submit and can upload pictures currently only support single */+ (NSString *) Postrequestwithurl: (nsstring *) URL  //In                            Postparems: (Nsmutabledictionary *) Postparems//In submit parameter according to set                            Picfilepath: (NSString *) Picfilepath  //In upload picture path                            picfilename: (NSString *) Picfilename;  In Upload image name/** * Hair repair picture size */+ (UIImage *) Imagewithimagesimple: (uiimage*) Image scaledtosize: (cgsize) newsize;/** * Save Picture */+ (NSString *) SaveImage: (UIImage *) tempimage withname: (NSString *) imagename;/** * Generate GUID */+ (NSString *) generateuuidstring; @end

requestpostuploadhelper.m//demodes////Created by Zhang Hao on 13-5-8.//Copyright (c) 2013 Zhang Hao. All rights reserved.//#import "RequestPostUploadHelper.h" @implementation requestpostuploadhelperstatic NSString * Const FORM_FLE_INPUT = @ "file"; + (NSString *) Postrequestwithurl: (nsstring *) URL//in Postparems: (                     Nsmutabledictionary *) Postparems//In Picfilepath: (NSString *) Picfilepath//In  Picfilename: (NSString *) picfilename;    in{nsstring *twitterfon_form_boundary = @ "0xKhTmLbOuNdArY";                                                           Request nsmutableurlrequest* request = [Nsmutableurlrequest Requestwithurl:[nsurl Urlwithstring:url] based on URL initialization                                                       Cachepolicy:nsurlrequestreloadignoringlocalcachedata    TIMEOUTINTERVAL:10];    Dividing line--aab03x nsstring *mpboundary=[[nsstring alloc]initwithformat:@ "--%@", twitterfon_form_boundary]; Terminator aab03x--NSString *endmpboundary=[[nsstring alloc]initwithformat:@ "%@--", mpboundary];    Get the image data nsdata* data;        if (picfilepath) {UIImage *image=[uiimage imagewithcontentsoffile:picfilepath];            Determine if the picture is a PNG file if (uiimagepngrepresentation (image)) {//returns to a PNG image.        data = uiimagepngrepresentation (image);            }else {//return to JPEG image.        data = uiimagejpegrepresentation (image, 1.0);    }}//http the body string nsmutablestring *body=[[nsmutablestring alloc]init];        The collection of all keys for the collection of parameters Nsarray *keys= [Postparems AllKeys];              Traverse keys for (int i=0;i<[keys count];i++) {//Get current key nsstring *key=[keys objectatindex:i];        Add dividing line, newline [body appendformat:@ "%@\r\n", mpboundary];        Add field name, change 2 lines [Body appendformat:@ "content-disposition:form-data; name=\"%@\ "\r\n\r\n", key];                 Add the value of the field [body appendformat:@ "%@\r\n", [Postparems Objectforkey:key]]; NSLog (@ "Add Value of field ==%@", [Postparems Objectforkey:key]);            } if (Picfilepath) {////add dividing line, newline [body appendformat:@ "%@\r\n", mpboundary]; Declare pic field, file name boris.png [body appendformat:@ "content-disposition:form-data; name=\"%@\ "; filename=\"%@\ "\ r \ n", form        _fle_input,picfilename]; Declare the format of the uploaded file [body appendformat:@ "content-type:image/jpge,image/gif, Image/jpeg, Image/pjpeg, image/pjpeg\r\n\r\n"]    ;    }//Declaration terminator:--aab03x--nsstring *end=[[nsstring alloc]initwithformat:@ "\r\n%@", endmpboundary];    Declaration Myrequestdata, used to put the HTTP body nsmutabledata *myrequestdata=[nsmutabledata data];    Converts the body string to UTF8 format binary [myrequestdata appenddata:[body datausingencoding:nsutf8stringencoding];    if (Picfilepath) {//Add the data of image to [Myrequestdata Appenddata:data];      }//Add terminator--aab03x--[Myrequestdata appenddata:[end datausingencoding:nsutf8stringencoding]; Set the value of Content-type in Httpheader nsstring *content=[[nsstring ALLOC]INITWITHFormat:@ "Multipart/form-data;    boundary=%@ ", twitterfon_form_boundary];    Set httpheader [Request Setvalue:content forhttpheaderfield:@ "Content-type"]; Set content-length [Request Setvalue:[nsstring stringwithformat:@ "%d", [Myrequestdata Length]] forhttpheaderfield:@ "    Content-length "];    Set HTTP body [request Sethttpbody:myrequestdata];            HTTP method [Request sethttpmethod:@ "POST"];    Nshttpurlresponse *urlresponese = nil;    Nserror *error = [[Nserror alloc]init]; nsdata* resultdata = [nsurlconnection sendsynchronousrequest:request returningresponse:&urlresponese error:&    ERROR];    nsstring* result= [[NSString alloc] Initwithdata:resultdata encoding:nsutf8stringencoding];        if ([Urlresponese StatusCode] >=200&&[urlresponese statuscode]<300) {NSLog (@ "Return results =====%@", result);    return result; } return nil;} /** * Hair repair picture size */+ (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;}        /** * Save Picture */+ (NSString *) SaveImage: (UIImage *) tempimage withname: (NSString *) imagename{nsdata* imageData;        Determine if the picture is not a PNG file if (uiimagepngrepresentation (tempimage)) {//returns as a PNG image.    ImageData = Uiimagepngrepresentation (tempimage);        }else {//return to JPEG image.    ImageData = UIImageJPEGRepresentation (Tempimage, 1.0);        } nsarray* paths = Nssearchpathfordirectoriesindomains (Nsdocumentdirectory,nsuserdomainmask,yes);        nsstring* documentsdirectory = [Paths objectatindex:0];    nsstring* fullpathtofile = [Documentsdirectory stringbyappendingpathcomponent:imagename];    Nsarray *nameary=[fullpathtofile componentsseparatedbystring:@ "/"]; NSLog (@ "===fullpathtofile===%@ ", fullpathtofile);        NSLog (@ "===filename===%@", [Nameary objectatindex:[nameary count]-1]);    [ImageData Writetofile:fullpathtofile Atomically:no]; return fullpathtofile;} /** * Generate GUID */+ (NSString *) generateuuidstring{//Create a new UUID which you own cfuuidref uuid = Cfuuidcreate (KC        Fallocatordefault); Create a new Cfstringref (toll-free bridged to nsstring)//So you own nsstring *uuidstring = (NSString *) Cfuui        Dcreatestring (Kcfallocatordefault, UUID);        Transfer ownership of the string//to the autorelease pool [uuidstring autorelease];        Release the UUID cfrelease (UUID); return uuidstring;} @end

DEMO

  uploadviewcontroller.h//  demodes////  Created by Zhang Hao on 13-5-6.//  Copyright (c) 2013 Zhang Hao. All rights reserved.//#import <UIKit/UIKit.h> @interface uploadviewcontroller:uiviewcontroller< uiactionsheetdelegate,uiimagepickercontrollerdelegate>-(ibaction) Onclickuploadpic: (ID) sender;-(void) snapimage;//photo-(void) pickimage;//from the album-(UIImage *) Imagewithimagesimple: (uiimage*) Image scaledtosize: (cgsize) newsize;-(void) SaveImage: (UIImage *) tempimage withname: (NSString *) imagename;-(ibaction) Onpostdata: (ID) sender;-( NSString *) generateuuidstring; @end

uploadviewcontroller.m//demodes////Created by Zhang Hao on 13-5-6.//Copyright (c) 2013 Zhang Hao. All rights reserved.//#import "UploadViewController.h" #import "RequestPostUploadHelper.h" @interface Uploadviewcontroller () @endNSString *[email protected] ""; @implementation uploadviewcontroller-(ID) Initwithnibname: (NSString *) Nibnameornil Bundle: (NSBundle *) nibbundleornil{self = [Super Initwithnibname:    Nibnameornil Bundle:nibbundleornil]; if (self) {//Custom initialization} return to self;}    -(void) viewdidload{[Super Viewdidload]; Do any additional setup after loading the view from its nib.}    -(void) didreceivememorywarning{[Super didreceivememorywarning]; Dispose of any resources the can be recreated.} -(Ibaction) Onclickuploadpic: (ID) Sender {uiactionsheet *menu=[[uiactionsheet alloc] initwithtitle:@ "Upload picture" delegate:    Self cancelbuttontitle:@ "Cancel" destructivebuttontitle:nil otherbuttontitles:@ "photo upload" @ "Upload from album", 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"); } [Actionsheet release];}    Photo-(void) snapimage{Uiimagepickercontroller *ipc=[[uiimagepickercontroller alloc] init];    Ipc.sourcetype=uiimagepickercontrollersourcetypecamera;    ipc.delegate=self;    Ipc.allowsediting=no;    [Self PRESENTMODALVIEWCONTROLLER:IPC animated:yes];    }//from the album-(void) pickimage{Uiimagepickercontroller *ipc=[[uiimagepickercontroller alloc] init];    Ipc.sourcetype=uiimagepickercontrollersourcetypephotolibrary;    ipc.delegate=self;    Ipc.allowsediting=no; [Self PRESENTMODALVIEWCONTROLLER:IPC animated:yes];} -(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 dismissmodalviewcontrolleranimated:yes]; [Picker release];} -(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 = 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 stringbyappendingpathcompone        Nt: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];    }-(ibaction) Onpostdata: (ID) Sender {nsmutabledictionary * dir=[nsmutabledictionary dictionarywithcapacity:7];    [dir setvalue:@ "Save" forkey:@ "M"];    [dir setvalue:@ "ios upload try" forkey:@ "title"];    [dir setvalue:@ "ios upload try" forkey:@ "content"]; [Dir setvalue:@ "forkey:@" Clubuserid "];    [dir setvalue:@ "1" forkey:@ "Clubsectionid"];    [dir setvalue:@ "192.168.0.26" forkey:@ "IP"];    [dir setvalue:@ "asfdfasdfasdfasdfasdfasd=" forkey:@ "Sid"];    NSString *[email protected] "Http://192.168.0.26:8090/api/club/topicadd.do?m=save";    NSLog (@ "======= upload"); if ([Tmp_upload_img_path isequaltostring:@ "]) {[Requestpostuploadhelper postrequestwithurl:url postParems:dir PicFi    Lepath:nil Picfilename:nil];        }else{NSLog (@ "icon upload");       Nsarray *nameary=[tmp_upload_img_path componentsseparatedbystring:@ "/"]; [Requestpostuploadhelper postrequestwithurl:url postparems:dir Picfilepath:tmp_upload_img_path picFileName:[    Nameary objectatindex:[nameary count]-1];; }}-(NSString *) generateuuidstring{//Create a new UUID which you own cfuuidref uuid = Cfuuidcreate (Kcfallocatorde        fault); Create a new Cfstringref (toll-free bridged to nsstring)//So you own nsstring *uuidstring = (NSString *) Cfuui DcreatesTring (Kcfallocatordefault, UUID);        Transfer ownership of the string//to the autorelease pool [uuidstring autorelease];        Release the UUID cfrelease (UUID); return uuidstring;} @end
Original: http://www.cnblogs.com/skyblue/archive/2013/05/08/3067108.html

iOS Upload Image Method class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.