IOS uploads images to the server and several methods received by the server PHP. 1. convert the images to Base64 encoding and POST Upload. PHP decodes Base64 into binary and then writes out the file. Disadvantage: you cannot upload large images.
// IOS (Swift) func upload (image: UIImage, url: String) {let imageData = UIImageJPEGRepresentation (image, 0.3) // convert the image to NSData in jpeg format, compressed to 0.3 let imageStr = imageData ?. Base64encodedstringwitexceptions (. Encoding64CharacterLineLength) // convert the image to a base64 string let params: NSDictionary = ["file": imageStr!] Let manager = AFHTTPRequestOperationManager () // The POST Upload method is used, because there is no limit on the length of the POST manager. POST (url, parameters: params, success: {(_: AFHTTPRequestOperation !, Response: AnyObject !) In // success}) {(_: AFHTTPRequestOperation !, _: NSError !) In // failed }}
2. AFNetworking Upload. The PHP side receives images through the normal webpage Upload method.
Static func uploadPortrait (image: UIImage, url: String) {let manager = AFHTTPRequestOperationManager () // fromData: AFN encapsulated http header class, you can add request body manager. POST (url, parameters: [:], constructingBodyWithBlock: {(fromData: AFMultipartFormData !) In let pngData = UIImagePNGRepresentation (image) // name must be the same as the parameter name received by the backend PHP ($ _ FILES ["file"]) // fileName is the image name fromData. appendPartWithFileData (pngData, name: "file", fileName: "image.png", mimeType: "image/png") // let your data = UIImageJPEGRepresentation (image, 0.3) // fromData. appendPartWithFileData (response data, name: "file", fileName: "image.jpg", mimeType: "image/jpeg")}, success: {(operation: AFHTT PRequestOperation !, Response: AnyObject !) In // success}) {(operation: AFHTTPRequestOperation !, Error: NSError !) In // failed }}
0) {echo $ _ FILES ["file"] ["error"]; // error code} else {$ fillname = $ _ FILES ['file'] ['name']; // Get the full name of the file $ dotArray = explode ('. ', $ fillname); // use. split the string to get the array $ type = end ($ dotArray); // get the last element: file suffix $ path = ".. /portrait /". md5 (uniqid (rand ())). '. '. $ type; // Generate a random and unique name move_uploaded_file (// copy from the temporary directory to the target directory $ _ FILES ["file"] ["tmp_name"], // name of the temporary copy of the file stored on the server $ path); echo "successful" ;}} else {echo "incorrect file type" ;}?>
3. the image is encapsulated in the request body of the Http request message and uploaded. It is also the principle of AFN Upload.
// Use OC encapsulation # import
@ Interface RequestPostUploadHelper: NSObject + (NSMutableURLRequest *) uploadImage :( NSString *) url uploadImage :( UIImage *) uploadImage params :( callback *) params; @ end # import "RequestPostUploadHelper. h "@ implementation RequestPostUploadHelper + (NSMutableURLRequest *) uploadImage :( NSString *) url uploadImage :( UIImage *) uploadImage params :( NSMutableDictionary *) params {[params setObject E forKey: @ "file"]; // The demarcation line identifier NSString * TWITTERFON_FORM_BOUNDARY = @ "AaB03x"; // initialize the request NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: url] cachePolicy: hour timeoutInterval: 10]; // demarcation line -- AaB03x NSString * MPboundary = [[NSString alloc] initWithFormat: @ "-- % @", TWITTERFON_FORM_BOUNDARY]; // Terminator AaB03x -- NSString * endMPbound Ary = [[NSString alloc] initWithFormat: @ "% @ --", MPboundary]; // UIImage * image = [params objectForKey: @ "file"]; // Obtain the image's data NSData * data = UIImagePNGRepresentation (image); // The http body string NSMutableString * body = [[NSMutableString alloc] init]; // NSArray * keys = [params allKeys]; // traverses keys for (int I = 0; I <[keys count]; I ++) {// Obtain the current key NSString * key = [keys objectAtIndex: I]; // if the key is not f Ile, indicating that value is a character type, such as name: Boris if (! [Key isEqualToString: @ "file"]) {// add a line break, line feed [body appendFormat: @ "% @ \ r \ n", MPboundary]; // add the field name, for two rows [body appendFormat: @ "Content-Disposition: form-data; name = \ "% @ \" \ r \ n ", key]; // add the field value [body appendFormat: @ "% @ \ r \ n", [params objectForKey: key] ;}/// add a line break, line feed [body appendFormat: @ "% @ \ r \ n", MPboundary]; // specifies the filefield. the file name is image.png [body appendFormat: @ "Content-Disposition: form-data; name = \" file \"; filename = \ "image.png \" \ r \ n "]; // declare the format of the uploaded file [body appendFormat: @" Content-Type: image/png \ r \ n "]; // declaration Terminator: -- AaB03x -- NSString * end = [[NSString alloc] initWithFormat: @ "\ r \ n % @", endMPboundary]; // declare myRequestData to put the http body NSMutableData * myRequestData = [NSMutableData data]; // convert the body string to a binary string in UTF8 format [myRequestData appendData: [body dataUsingEncoding: NSUTF8StringEncoding]; // add the image data to [myRequestData appendData: data]; // add the 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"]; return request;} @ end
// Use // Swiftstatic func uploadPortrait (image: UIImage, url: String) {// Use let request = RequestPostUploadHelper. uploadImage (url, uploadImage: image, params: [:]) // asynchronous network request NSURLConnection. sendAsynchronousRequest (request, queue: NSOperationQueue () {(response: NSURLResponse ?, Data: NSData ?, Error: NSError ?) In if error! = Nil {// failed} else {// succeeded }}}
4. convert the iOS image to NSData and upload it through POST. PHP receives the POST parameter, converts the NSData hexadecimal code to the binary code supported by PHP, and then writes the file to save it.
No way is found. after PHP receives the hexadecimal encoding, it cannot output the image after the algorithm is converted to binary.
5. binary POST Upload. PHP directly saves data as images
No way is found. The getBytes of NSData on iOS cannot be converted to binary.