iOS Development Web-File upload

Source: Internet
Author: User

When a file is uploaded, the POST request is used, and the data to be uploaded is usually stored in the request body. This article describes how to implement a file upload in iOS development without the help of a third-party framework.

Because of the complexity of the process, only some of the key code is posted.

Key code for the host controller:

Yyviewcontroller.m

 1 #import "YYViewController.h" 2 3 #define YYENCODE (str) [STR datausingencoding:nsutf8stringencoding] 4 5 @interface YY Viewcontroller () 6 7 @end 8 9 @implementation YYViewController10-(void) viewDidLoad12 {[Super viewdidload];1 4/additional setup after loading the view, typically from a nib.15}16-(void) Upload: (NSString *) name fi Lename: (NSString *) filename mimeType: (NSString *) mimeType data: (NSData *) data parmas: (Nsdictionary *) params18 {19//) Piece upload Nsurl *url = [Nsurl urlwithstring:@ "Http://192.168.1.200:8080/YYServer/upload"];21 nsmutableurlrequest *requ EST = [nsmutableurlrequest requestwithurl:url];22 request. HttpMethod = @ "POST"; 23 24//Set request body nsmutabledata *body = [Nsmutabledata data];26 27/**************      * File parameter ***************/28//parameter start flag [body Appenddata:yyencode (@ "--yy\r\n")];30//Name: Specify parameter name (must be consistent with server side) 31 FileName: file name nsstring *disposition = [NSString stringwithformat:@ "CoNtent-disposition:form-data; Name=\ "%@\"; Filename=\ "%@\" \ r \ n ", name, filename];33 [body appenddata:yyencode (disposition)];34 nsstring *type = [NSString str ingwithformat:@ "Content-type:%@\r\n", mimetype];35 [Body appenddata:yyencode (Type)];36 Notoginseng [Body appenddata:yy Encode (@ "\ r \ n")];38 [Body appenddata:data];39 [Body appenddata:yyencode (@ "\ r \ n")];40 41/*************** Normal         Parameter ***************/42 [params enumeratekeysandobjectsusingblock:^ (ID key, id obj, BOOL *stop) {43//Parameter start flag 44 [Body Appenddata:yyencode (@ "--yy\r\n")];45 nsstring *disposition = [NSString stringwithformat:@ "Content-Di Sposition:form-data; Name=\ "%@\" \ r \ n ", key];46 [body appenddata:yyencode (disposition)];47 [body appenddata:yyencode (@" \ r \ n ") ];49 [Body appenddata:yyencode (obj)];50 [body appenddata:yyencode (@ "\ r \ n")];51}];52 53/***** Parameter end ***************/54//Yy--\r\n55 [Body appenddata:yyencode (@ "--yy--\r\n")];56 request. Httpbody = body;57 58//Set Request header 59//Request body length [request setvalue:[nsstring stringwithformat:@ "%zd", Body.len Gth] forhttpheaderfield:@ "content-length"];61//Declare this post request is a file upload [request setvalue:@] multipart/form-data; bound Ary=yy "forhttpheaderfield:@" Content-type "];63 64//Send request [nsurlconnection sendasynchronousrequest:request Q Ueue:[nsoperationqueue Mainqueue] completionhandler:^ (nsurlresponse *response, NSData *data, NSError *connectionError {if (data) {nsdictionary *dict = [Nsjsonserialization jsonobjectwithdata:data options:nsjsonre         Adingmutableleaves error:nil];68 NSLog (@ "%@", dict), or else {NSLog (@ "upload failed"); 71 }72}];73}74-(void) Touchesbegan: (Nsset *) touches withevent: (uievent *) event76 {//Socket Implementation Breakpoint upload 78 7   9//apache-tomcat-6.0.41/conf/web.xml Find File MimeType80//UIImage *image = [UIImage imagenamed:@ "test"];81// NSData *filedata = uiimagepngrepresentation (image); [Self upload:@ "file" filename:@ "Test.png" mimetype:@ "image/pn G "Data:filedata parmas:@{@" username ": @" 123 "}];83 84//Send a request to a local file. nsurl *fileurl = [[NSBundle mainbundle      ] urlforresource:@ "Itcast.txt" withextension:nil];86 nsurlrequest *request = [Nsurlrequest requestwithurl:fileurl];87 Nsurlresponse *repsonse = nil;88 NSData *data = [Nsurlconnection sendsynchronousrequest:request returningResponse : &repsonse error:nil];89 90//Get mimeType91 NSLog (@ "%@", repsonse. MIMEType); [Self upload:@ "file" filename:@ "Itcast.txt" mimetype:repsonse.                                                                                               MIMEType Data:data parmas:@{93 @ "username": @ "999", 94 @ ' type ': @ ' XML '}];95}96 @end

Additional notes:

File upload request data format

MimeType of some files

iOS Development Web-File upload

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.