"IOS" File upload little note

Source: Internet
Author: User

iOS with the system-provided API can be implemented to achieve file upload and download, respectively, there are two ways. nsurlconnection and nsurlsession.

Where Nsurlconnection is a long-used way, nsurlsession is a new way out.


First, Post mode upload

The post submission information is used by default:*Content-type: application/x-www-form-urlencoded.*when entering Chinese,PostAutomatic escape mode(Automatic in Apple).
most websites in the country use this approachUploading Files(support for binary files)*Content-type:Multipart/form-data(Uploading Files)*will limit the size of the uploaded fileis generally2Mor smaller.


Uploading in Apple is a hassle. You need to stitch up the required string format for uploading before uploading. (Plus head)


Other platforms do a good bit of the possible encapsulation, do not need to stitch their own string format. So it's rarely uploaded in this way in iOS.

Example code:

#import "XNUploadFile.h" #define Ktimeout 5.0f@implementation xnuploadfile/** delimited string */static nsstring *boundarystr = @ "--    /** this upload flag string */static nsstring *randomidstr;/** Upload (PHP) script, receive file field */static nsstring *uploadid;-(instancetype) init{    self = [super init];        if (self) {/** This upload marked String */Randomidstr = @ "Itcastupload";    /** Upload (PHP) script, receive file field *//can consult the company's website development Programmer//or use Firebug to track and debug Uploadid = @ "UploadFile"; } return self;}  #pragma the mark-member method. Complete upload with nsurlsession-(void) UploadFile: (NSString *) path filename: (NSString *) filename completion: (void (^) (NSString * String) completion{//1. URL Hint: Really responsible for file upload is PHP file, not html file nsurl *url = [Nsurl urlwithstring:@ "http://localhost/new/        Post/upload.php "]; 2.        Request Nsurlrequest *request = [self Requestforuploadurl:url uploadfilename:filename localfilepath:path]; 3.        Session (Reply)//Global network reply, in order to facilitate the use of network services programmers nsurlsession *session = [Nsurlsession sharedsession]; 4. The task of data task-----/** urlsession, which is initiated by the reply, is done by default on other threads, and is asynchronous by default */[Session Datataskwithrequest:request Completionhand ler:^ (NSData *data, Nsurlresponse *response, Nserror *error) {id result = [nsjsonserialization jsonobjectw                Ithdata:data options:0 Error:null];                NSLog (@ "%@%@", result, [Nsthread CurrentThread]);            Dispatch_async (Dispatch_get_main_queue (), ^{if (completion) {completion (@ "Download complete");    }        });        }] [resume]; Nsurlsessiondatatask *task = [Session datataskwithrequest:request completionhandler:^ (NSData *data, NSURLResponse *r Esponse, Nserror *error) {////ID result = [nsjsonserialization jsonobjectwithdata:data options:0 Error:nul    L];    NSLog (@ "%@%@", result, [Nsthread CurrentThread]); Dispatch_async (Dispatch_get_main_queue (), ^{//if (completion) {//Compl    Etion (@ "Download complete"); //            }    //        });    //    }]; //5. Start a task//[task resume];} #pragma mark-Private method: spelling string/** stitching top String */-(NSString *) Topstringwithmimetype: (NSString *) MimeType uploadfile: (NSString *) up        loadfile{nsmutablestring *STRM = [nsmutablestring string];    [StrM appendformat:@ "%@%@\n", Boundarystr, Randomidstr];    [StrM appendformat:@ "content-disposition:form-data; name=\"%@\ "; filename=\"%@\ "\ n", Uploadid, UploadFile];        [StrM appendformat:@ "Content-type:%@\n\n", MimeType];    NSLog (@ "Top string:%@", StrM); return [StrM copy];}        /** stitching the bottom string */-(NSString *) bottomstring{nsmutablestring *STRM = [nsmutablestring string];    [StrM appendformat:@ "%@%@\n", Boundarystr, Randomidstr];    [StrM appendstring:@ "content-disposition:form-data; name=\" submit\ "\ n"];    [StrM appendstring:@ "submit\n"];        [StrM appendformat:@ "%@%@--\n", Boundarystr, Randomidstr];    NSLog (@ "bottom string:%@", StrM); return [StrM copy];} /** Specifies the mimetype */-(NSString *) of the full path file MimetypewithfilepAth: (NSString *) filepath{//1. Determine if the file exists if (![    [Nsfilemanager Defaultmanager] Fileexistsatpath:filepath]) {return nil; }//2.    Use the HTTP head method to get the uploaded file information nsurl *url = [Nsurl Fileurlwithpath:filepath];        Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url]; 3.    Call the synchronous method to get the file's mimetype nsurlresponse *response = nil;        [Nsurlconnection sendsynchronousrequest:request returningresponse:&response Error:NULL]; return response. MIMEType;} /** upload file network request */-(Nsurlrequest *) Requestforuploadurl: (nsurl *) URL uploadfilename: (NSString *) FileName Localfilepath: (    NSString *) filepath{//0. Get the uploaded file mimeType nsstring *mimetype = [self mimetypewithfilepath:filepath];        if (!mimetype) return nil; 1.    Stitching the data body to be uploaded nsmutabledata *datam = [Nsmutabledata data]; [Datam appenddata:[[self Topstringwithmimetype:mimetype Uploadfile:filename] datausingencoding:    Nsutf8stringencoding]]; Stitching the binary data of the uploaded file itself [Datam appenddata:[nsdata DatawitHcontentsoffile:filepath]];        [Datam appenddata:[[self bottomstring] datausingencoding:nsutf8stringencoding]; 2.    Set request Nsmutableurlrequest *requestm = [nsmutableurlrequest requestwithurl:url cachepolicy:0 TimeoutInterval:kTimeOut];    1> Set HTTP request mode Requestm.httpmethod = @ "POST";    2> setting Data Body requestm.httpbody = Datam; 3> Specifies content-type nsstring *typestr = [NSString stringwithformat:@ "multipart/form-data; boundary=%@", RandomIDStr    ];    [Requestm setvalue:typestr forhttpheaderfield:@ "Content-type"];    4> Specifies the data length nsstring *lengthstr = [NSString stringwithformat:@ "%@" @ ([Datam length])];        [Requestm setvalue:lengthstr forhttpheaderfield:@ "Content-length"]; return [requestm copy];}

Note:POSTwhen uploading,is aduplicate names are not allowedof the.(otherwise error)


Second, put the way to upload

Sessionin theUploadmethod can only be used forPUTUpload,cannot be used forPOSTUpload.

withPUTWay to uploadBenefits:(Authentication Required)*not likePOSTsame,spell a bunch of strings.*directlyBase64encode a bit of authentication, Sessionof theUploadOne call on the line..*no file size limit.*Instant MessagingIt 's a lot of use..(Send picture/Send Voice)

-(void) putfile{//1. The last URL to upload is the file name to be uploaded nsurl *url = [Nsurl urlwithstring:@ "HTTP://LOCALHOST/UPLOADS/ABCD"];//ABCD is File name//2.    Request Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url]; Request. HttpMethod = @ "PUT";//Request.        HttpMethod = @ "DELETE";    Set up user authorization//BASE64 encoding: A "most commonly used network encoding method" for encoding strings and binary data, which converts binary data to strings!    is the underlying algorithm of many cryptographic algorithms//BASE64 support anti-coding, is a bidirectional encoding scheme nsstring *AUTHSTR = @ "admin:123";    NSString *authbase64 = [NSString stringwithformat:@ "Basic%@", [self base64encode:authstr]];        [Request Setvalue:authbase64 forhttpheaderfield:@ "Authorization"]; 3.        Urlsession nsurlsession *session = [Nsurlsession sharedsession]; 4.    Task initiated by session nsurl *localurl = [[NSBundle mainbundle] urlforresource:@ "001.png" withextension:nil]; [[Session Uploadtaskwithrequest:request Fromfile:localurl completionhandler:^ (NSData *data, NSURLResponse *response, Nserror *error) {nsstring *result = [[NSSTring Alloc] Initwithdata:data encoding:nsutf8stringencoding];    NSLog (@ "Sesult--->%@%@", result, [Nsthread CurrentThread]); }] [resume];} -(NSString *) Base64Encode: (NSString *) str{//1. Converting strings to binary data nsdata *data = [Str datausingencoding:nsutf8stringenc        Oding]; 2.        The binary data is base64 encoded nsstring *result = [data base64encodedstringwithoptions:0];        NSLog (@ "base464-->%@", result); return result;}

The Put method corresponds to delete, which deletes the file uploaded by the put method.


Tips:session Use note

*Network Session,convenient for programmers to use Web services.*as:can get the current upload file progress.*nsurlsessionthe Task, by default, allAsynchronousof the.(working in other threads)*Taskis bySessionInitiated by.*Note Network requests are handled with error.*SessionThe default is pending,need toResumeto start ..

Reprint Please specify source:http://blog.csdn.net/xn4545945

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.