AFNetworking framework _ upload files or images to the server

Source: Internet
Author: User

AFNetworking framework _ upload files or images to the server

In this article, XXXXXXXXXX has your own Parameter

-(Void) uploadImageWithImage :( NSString *) imagePath

{

// Upload other required parameters

NSString * userId = XXXXXXXXXXX;

NSString * token = XXXXXXXXXXX;

// Upload request POST

AFHTTPClient * client = [AFHTTPClientclientWithBaseURL: [NSURLURLWithString: @ ""];


NSString * urlString = [NSStringstringWithFormat: @ "Upload server address];

NSDictionary * dic = [[NSDictionaryalloc] initWithObjectsAndKeys: userId, @ "XXXXXX", token, @ "XXXXXX", nil];

NSURLRequest * request = [clientmultipartFormRequestWithMethod: @ "POST" path: urlString parameters: dicconstructingBodyWithBlock: ^ (id formData ){

// Obtain the data to be uploaded

NSData * data = [NSDatadataWithContentsOfFile: imagePath];

// Use the current system event as the file name during upload

NSDateFormatter * formatter = [[NSDateFormatteralloc] init];

Formatter. dateFormat = @ "yyyyMMddHHmmss ";

NSString * str = [formatter stringFromDate: [NSDate date];

NSString * fileName = [NSStringstringWithFormat: @ "symbol @.jpg", str];

/*

This method parameter

1. [binary data] to be uploaded

2. The [field "file"] for processing files in [upload. php] on the website

3. [file name] to be saved on the server

4. Upload the [mimeType] of the file

*/


// Fields and types of files uploaded by the server

[FormData appendPartWithFileData: data name: @ "XXXXX" fileName: fileName mimeType: @ "image/jpg/file"];

}];

// 3. operation-encapsulated urlconnetion

AFHTTPRequestOperation * op = [[AFHTTPRequestOperationalloc] initWithRequest: request];

[OpsetCompletionBlockWithSuccess: ^ (AFHTTPRequestOperation * operation, id responseObject ){

NSLog (@ "uploaded ");

} Failure: ^ (AFHTTPRequestOperation * operation, NSError * error ){

NSLog (@ "Upload Failed-> % @", error );

}];

// Execute

[Client. operationQueueaddOperation: op];

}

Related Article

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.