[IOS] File Upload note, ios note

Source: Internet
Author: User

[IOS] File Upload note, ios note

The APIS provided by the system can be used in iOS to upload and download files in two ways.NSURLConnectionAndNSURLSession.

NSURLConnection is a method that has been in use for a long time, And NSURLSession is a new method.


I. POST upload

By default, the POST method uses: * Content-Type: application/x-www-form-urlencoded. * to input Chinese characters, the post method is automatically escaped (automatically in Apple ).
Most websites in China use this method to upload files (binary files are supported) * Content-Type: multipart/form-data (File Upload) * The size of the uploaded file is generally limited to 2 MB or smaller.


Uploading in Apple is very troublesome. You must splice the string format required for upload before uploading. (Add the header)


Other platforms may be well encapsulated and do not need to splice strings themselves. Therefore, in iOSThis method is rarely used for upload..

Sample Code:

# Import "XNUploadFile. h "# define kTimeOut 5.0f @ implementation XNUploadFile/** separator string */static NSString * boundaryStr = @" -- ";/** this upload ID string */static NSString * randomIDStr; /** In the upload (php) script, the Receiving File field */static NSString * uploadID;-(instancetype) init {self = [super init]; if (self) {/** the ID string for this upload */randomIDStr = @ "itcastupload";/** In the upload (php) script, receiving File fields * // consult the company's website development programmer // or use FireBug to track and debug uploadID = @ "uploa DFile ";}return self ;}# pragma mark-member method. use NSURLSession to complete upload-(void) uploadFile :( NSString *) path fileName :( NSString *) fileName completion :( void (^) (NSString * string) completion {// 1. url prompt: PHP files are actually responsible for file uploads, not html files NSURL * url = [NSURL URLWithString: @ "http: // localhost/new/post/upload. php "]; // 2. request NSURLRequest * request = [self requestForUploadURL: url uploadFileName: fileName localFilePath: Path]; // 3. session (session) // global network session. To make it easier for programmers to use the network service NSURLSession * session = [NSURLSession sharedSession]; // 4. data task> task is a/** URLSession task initiated by a session. By default, tasks work in other threads. The tasks are asynchronous by default. */[[session dataTaskWithRequest: request completionHandler: ^ (NSData * data, NSURLResponse * response, NSError * error) {id result = [NSJSONSerialization JSONObjectWithData: data options: 0 error: NULL]; NSLog (@ "% @", result, [NSThread cu RrentThread]); dispatch_async (dispatch_get_main_queue (), ^ {if (completion) {completion (@ "download completed") ;}});}] resume]; // required * task = [session dataTaskWithRequest: request completionHandler: ^ (NSData * data, NSURLResponse * response, NSError * error) {// id result = [NSJSONSerialization JSONObjectWithData: data options: 0 error: NULL]; // NSLog (@ "% @", result, [NSThread currentThre Ad]); // dispatch_async (dispatch_get_main_queue (), ^ {// if (completion) {// completion (@ "download completed "); ///} //}); //}]; // 5. start the task // [task resume] ;}# pragma mark-Private method: Spell string/** splice top string */-(NSString *) topStringWithMimeType :( NSString *) mimeType uploadFile :( NSString *) uploadFile {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", mimeType]; NSLog (@ "Top string: % @", strM ); return [strM copy];}/** concatenate 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];} /** specify the mimeType of the full path file */-(NSString *) mimeTypeWithFilePath :( NSString *) filePath {// 1. determine whether the object exists if (! [[NSFileManager defaultManager] fileExistsAtPath: filePath]) {return nil;} // 2. use the http head method to obtain the uploaded file information NSURL * url = [NSURL fileURLWithPath: filePath]; NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url]; // 3. call the synchronization method to obtain the MimeType NSURLResponse * response = nil; [NSURLConnection sendSynchronousRequest: request returningResponse: & response error: NULL]; return response. MIMEType ;}/** File Transfer Network Request */-(NSURLRequest *) requestForUploadURL :( NSURL *) url uploadFileName :( NSString *) fileName localFilePath :( NSString *) filePath {// 0. obtain the mimeType NSString * mimeType = [self mimeTypeWithFilePath: filePath]; if (! MimeType) return nil; // 1. concatenate the data body NSMutableData * dataM = [NSMutableData data]; [dataM appendData: [self topStringWithMimeType: mimeType uploadFile: fileName] dataUsingEncoding: Upload]; // concatenate the binary data of the uploaded file [dataM appendData: [NSData dataWithContentsOfFile: filePath]; [dataM appendData: [self bottomString] dataUsingEncoding: NSUTF8StringEncoding]; // 2. set the request NSMutableURLRequest * requestM = [NSMutableURLRequest requestWithURL: url cachePolicy: 0 timeoutInterval: kTimeOut]; // 1> set the HTTP Request Method requestM. HTTPMethod = @ "POST"; // 2> set the data body requestM. HTTPBody = dataM; // 3> specify Content-Type NSString * typeStr = [NSString stringWithFormat: @ "multipart/form-data; boundary = % @", randomIDStr]; [requestM setValue: typeStr forHTTPHeaderField: @ "Content-Type"]; // 4> specify the Data Length NSString * lengthStr = [NSString stringWithFormat: @ "% @", @ ([dataM length])]; [requestM setValue: lengthStr forHTTPHeaderField: @ "Content-Length"]; return [requestM copy];}

Note: During POST upload, duplicate names are not allowed. (otherwise, an error occurs)


Ii. PUT upload

The upload method in the session can only be used for PUT upload and cannot be used for POST upload.

Advantages of using PUT to upload: (authentication required) * you do not need to splice a bunch of strings like POST. * directly encode the base64 encoding for identity authentication. the upload of the session can be called once. * There is no file size limit. * instant messaging is mostly used. (send images/Voice)

-(Void) putFile {// 1. the last url is the file name to be uploaded. NSURL * url = [NSURL URLWithString: @ "http: // localhost/uploads/abcd"]; // abcd indicates the file name. // 2. request NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url]; request. HTTPMethod = @ "PUT"; // request. HTTPMethod = @ "DELETE"; // sets user authorization // BASE64 encoding: The most common Network encoding method used to encode strings and binary data ", this encoding can convert binary data into strings! // Is the underlying algorithm of many encryption algorithms // BASE64 supports anti-encoding. It 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. 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. convert the string to binary data NSData * data = [str dataUsingEncoding: NSUTF8StringEncoding]; // 2. base64 encoded binary data NSString * result = [data base64encodedstringwitexceptions: 0]; NSLog (@ "base464 --> % @", result); return result ;}

The PUT method corresponds to the DELETE method. DELETE is used to DELETE objects uploaded by the PUT method.


TIPS: session usage notes

* Network sessions facilitate programmers to use network services. * For example, you can get the progress of the file being uploaded. * NSURLSession tasks are asynchronous by default. (working in other threads) * A Task is initiated by a session. * handle all network requests with errors. * The session is suspended by default and can be started only after resume.

Reprinted please indicate the source: http://blog.csdn.net/xn4545945


Ios file write operations and file upload to server

The problem you are talking about is to upload a file to the server. Use more post requests. Both NSURLConnection and ASI can be used. The process is clear and you don't know which part of the process is wrong. Write files? Transfer files?
 
How to upload audio files to the server

Upload the file in the form of body to the server NSFileHandle * handler = [NSFileHandle fileHandleForReadingAtPath: _ fileURL];
[Handler seekToFileOffset :( unsigned long) _ range. location];
NSData * body = [handler readDataOfLength: _ range. length];

NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: url];
[Request setHTTPMethod: @ "POST"];
[Request setValue: @ "video/mp4" forHTTPHeaderField: @ "Content-Type"];
[Request setValue: [NSString stringWithFormat: @ "% d", body. length] forHTTPHeaderField: @ "Content-Length"];
[Request setValue: @ "no-cache" forHTTPHeaderField: @ "Cache-Control"];
[Request setHTTPBody: body];

Then the server receives the body binary stream.

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.