PHP with jquery plugin ajaxfileupload implementation of asynchronous upload file instance _php instance

Source: Internet
Author: User
Tags rtrim strcmp
Usually use more jquery image upload plugin is uploadify this plug-in, the effect is very good, but because the phone does not support Flash, so have to find a file upload plugin to use. Later found ajaxfileupload This plugin is very good, so use this plugin to do asynchronous upload file effect. There are many articles on the internet for the use of Ajaxfileupload plug-ins, but I found that there is no PHP version, so this time the server side of the processing using PHP language to handle.

I. Detailed syntax parameters of Ajaxfileupload Plugin

  principle:Ajaxfileupload is implemented by monitoring the OnLoad method of the IFrame, and when processing from the server is done, the OnLoad event that triggers the IFRAME invokes its binding method. Gets the data body returned by the server in the iframe in the bound method (supported plain text, Json,xml,script, HTML)

  Syntax: $.ajaxfileupload ([options])

Second, let's look at how to use

1, first introduce ajaxfileupload this plugin.

Here I use is jq1.11.1 version, online has said JQ version and ajaxfileupload version to correspond will not have abnormal error, anyway I now this no error.

2, paste the code of the HTML.

      Photo of your valid passport:            

Note: Please upload a picture of your hand-held document, making sure that the document information in the photo is legible.

The main point here isThis code, the other no tube, because here I am on the phone side, with the Jquerymobile plugin.

3, to the JS code for processing.

$ (document). Bind (' Pageinit ', function () {//Photo asynchronously uploads $ (' #id_photos '). Change (function () {///here uses the Change event, when the selected good picture opens, This event is triggered when the window is closed  $.ajaxfileupload ({  URL: '/uploader/',//script path for processing pictures  type: ' Post ',  //Submit in the way  Secureuri: False,//whether to enable secure commit  Fileelementid: ' Id_photos ',  //file control ID  dataType: ' json ',//The data type returned by the server    success:   function (data, status) {//The handler function that executes automatically after a successful commit   if (1! = data.total) return;  Because this refers to the permission to upload a single picture, so the number if not 1, that is the wrong   var url = data.files[0].path;   $ ('. Id_photos '). empty ();   The effect here is: When the successful upload will return a JSON data, there is a URL, take out the URL assigned to the IMG tag, and then appended to the. Id_photos class shows the picture   $ ('. Id_photos '). Append (");   $ ('. Upload-box '). Remove ();  },  error:function (data, status, E) {//submit failed automatically executed handler   alert (e);}  )});

Here I have a basic comment on the code of each line to make it easy for everyone to understand. The process is to upload the image to uploader.php, processing the successful return of the JSON data, and then remove the URL value in the JSON, assign it to the IMG tag, and then append the IMG tag to the page display.

Here I enclose the data returned by JSON:

{"Total": 1, "Success": 1, "Files": [  {   "SrcName": "3.jpg",   "error": 0,   "size": 10715, "   type": " Image/jpeg ",   " Success ": True,   " path ":" http://m.kellyblog.com/upload/20150528/ 857f4a35664b4a665e713322306d73b2.0x124x126.jpg ",   " width ": 124,   " height ": 126  }]}

The pre-upload HTML page is like this:

After the successful asynchronous upload, the HTML page effect is like this:

  

4. See how PHP is handled

Class Uploadercontroller extends Xxxx_controller {public Function index () {$files = array (); $success = 0;   User statistics How many images were uploaded successfully with foreach ($_files as $item) {$index = count ($files); $files [$index] [' srcname '] = $item [' name ']; The original name of the uploaded image $files [$index] [' error '] = $item [' ERROR '];  The error code associated with the file upload $files [$index] [' size '] = $item [' Size '];  The size of the uploaded file, in bytes $files [$index] [' type '] = $item [' type '];   The MIME type of the file requires the browser to provide support for that information, such as "Image/gif" $files [$index] [' success '] = false;    This is used to flag whether the image was successfully uploaded $files [$index] [' path '] = ';   Save picture Path//Receive process there is no error if ($item [' ERROR ']! = 0) Continue;    Determine if the image can be uploaded if (!is_uploaded_file ($item [' tmp_name ')) {$files [$index] [' ERROR '] = 8000;   Continue   }//extension $extension = ';   if (strcmp ($item [' type '], ' image/jpeg ') = = 0) {$extension = '. jpg ';   } else if (strcmp ($item [' type '], ' image/png ') = = 0) {$extension = '. png ';   } else if (strcmp ($item [' type '], ' image/gif ') = = 0) {$extension = '. gif '; } else {//if type is not above three, we will intercept the judgment from the original name of the image to obtain (in strict) $substr = STRRCHR ($item [' name '], '. ');     if (FALSE = = $substr) {$files [$index] [' error '] = 8002;    Continue }//Get the extension of the meta-name and assign the corresponding value to type by extension if (strcasecmp ($substr, '. jpg ') = = 0 | | strcasecmp ($SUBSTR, '. jpeg ') = = 0 | | strcas ECMP ($substr, '. jfif ') = = 0 | |    STRCASECMP ($substr, '. Jpe ') = = 0) {$files [$index] [' type '] = ' image/jpeg ';    } else if (strcasecmp ($substr, '. png ') = = 0) {$files [$index] [' type '] = ' image/png ';    } else if (strcasecmp ($substr, '. gif ') = = 0) {$files [$index] [' type '] = ' image/gif ';     } else {$files [$index] [' error '] = 8003;    Continue   } $extension = $substr;   }//Encrypt temporary file names for subsequent generation of complex new filenames $MD 5 = md5_file ($item [' tmp_name ']);   Get the size of the picture $imageInfo = getimagesize ($item [' tmp_name ']);   $rawImageWidth = $imageInfo [0];   $rawImageHeight = $imageInfo [1]; Set the image upload path, placed in the upload folder, in the month and day to generate folder classification store,//rtrim (Base_url (), '/') is actually the root directory of the site, we handle $path = RTrim (Base_url (), '/'). '/upload/'. DatE (' Ymd ').   '/';   Make sure the catalogue is writable Ensure_writable_dir ($path);   File name $name = "$md 5.0x{$rawImageWidth}x{$rawImageHeight} {$extension}"; Add image file does not change, that is, there is no need to repeat the upload, does not exist upload $ret = file_exists ($path. $name)?   True:move_uploaded_file ($item [' Tmp_name '], $serverPath. $name);    if ($ret = = = False) {$files [$index] [' error '] = 8004;   Continue  } else {$files [$index] [' path '] = $path. $name;   Save picture Path $files [$index] [' success '] = true; Image upload Success Logo $files [$index] [' width '] = $rawImageWidth; Image width $files [$index] [' height '] = $rawImageHeight; Picture height $success + +; Success +1}}//The image has been returned in JSON form to the JS processing page, where you can change to their own JSON return processing code echo json_encode (' total ' = count ($files), ' suc Cess ' = $success, ' files ' = $files,)); }}/********************************* Split *************************************************///Here I enclose ensure_writable The Code of the _dir () function/*** ensure that the folder exists and is writable * * @param string $dir */function ensure_writable_dir ($dir) {if (!file_exists ($dir)) {mkdir ($ Dir, 0766, True);  chmod ($dir, 0766); chmod ($dir, 0777);  } else if (!is_writable ($dir)) {chmod ($dir, 0766);  chmod ($dir, 0777);  if (!is_writable ($dir)) {throw new Filesystemexception ("Directory $dir not Writable"); } }}

The code is basically added to the comments, easy to understand, although the use of PHP processing image upload, but you understand the upload program code to deal with the logic of the idea, the idea for use in. NET or Java is still possible.

The above is the use of jquery plugin ajaxfileupload asynchronous upload files of the entire analysis process, I hope that everyone's learning is helpful.

  • 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.