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

Source: Internet
Author: User
Tags chmod php language rtrim strcmp

Usually use more than the jquery image upload plugin is uploadify This plug-in, the effect is very good, but because the mobile phone does not support Flash, so we have to find a file upload plug-in to use. Later found Ajaxfileupload This plug-in is very good, so use this plug-in to do the asynchronous upload file effect. There are also many articles on the use of Ajaxfileupload plug-ins online, but I found no PHP version, so the server side of the processing using the PHP language to deal with.

First, the detailed ajaxfileupload plug-in syntax parameters

  principle:ajaxfileupload is realized by listening to the OnLoad method of IFRAME, when processing from the service end, it triggers the onload event of the IFRAME to call 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, we'll see how to use

1, first introduced ajaxfileupload this plug-in.

<script src= "Jquery-1.11.1.js" type= "Text/javascript" ></script>
<script src= "Ajaxfileupload.js" "Type=" Text/javascript "></script>

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

2, paste the HTML code.

  <div data-role= "Fieldcontain" class= "Upload-box" > <label for= "id_photos" ><span class=
    "Red" >* </span> your valid documents according to:</label>
     <input type= "file" id= "Id_photos" name= "Id_photos" value= "Upload" style= " Filter:alpha (opacity=10);-moz-opacity:10;opacity:10; "/>   
    <p style=" Margin-top:0.5em;color: #999; font-size:11pt; " > Note: Please upload the bust of the hand ID card, please make sure the document information is legible and readable in the photo. </p>
  </div>
  <div class= "Id_photos" >
   
  

The main thing here is <input type= "file" id= "Id_photos" name= "Id_photos" value= "upload" > This code, the other does not have to tube, because here I am on the handset end, The Jquerymobile plugin is used.

3, to the JS code for processing.

$ (document). Bind (' Pageinit ', function () {
 //Photo asynchronously upload
 $ (' #id_photos '). Change (function () {//Where the Change event is used, This event
  $.ajaxfileupload ({
  URL: '/uploader/',///Process script path
  type: ' Post ',//  Submit mode
  ) When a good picture is opened and the window is closed Secureuri:false//Whether to enable secure commit
  Fileelementid: ' Id_photos ',  //file control ID
  dataType: ' json ',//server returned data type    
  success:function (data, status) {//(
   1!= data.total) return when the processing function is automatically executed after the successful submission;  Because this refers to allow the upload of a single picture, so if the number is not 1, that is the error of the
   var url = data.files[0].path;
   $ ('. Id_photos '). empty ();
   The effect here is: When a successful upload will return a JSON data, there is a URL, remove the URL assigned to the IMG tag, and then append to the. Id_photos class shows the picture
   $ ('. Id_photos '). Append ('  
 

Here I have a basic comment on each line of code that is easy to understand. The process is to upload the image to the uploader.php to process, processing the successful return of the JSON data, and then take out the URL value in JSON, assign it to the IMG tag, and then append the img tag with 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 HTML page before uploading is like this:

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

  

4, see how PHP is handled

Class Uploadercontroller extends Xxxx_controller {public Function index () {$files = array (); $success = 0;

   User statistics How many pictures uploaded succeeded foreach ($_files as $item) {$index = count ($files); $files [$index] [' srcname '] = $item [' name ']; Upload the original name of the picture $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, which requires the browser to provide support for the information, such as "Image/gif" $files [$index] [' success '] = false;    This is used to flag whether the picture is uploaded successfully $files [$index] [' path '] = ';
   The stored image Path//Receive process has no error if ($item [' ERROR ']!= 0) continue;
    Judge whether the picture can upload 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, we will intercept the judgment from the original name of the picture to get (in rigor) $substr = STRRCHR ($item [' name '], '. ');
     if (FALSE = = $substr) {$files [$index] [' error '] = 8002;
    Continue //Gets the name extension, and assigns the value to the type by extension if (strcasecmp ($substr, '. jpg ') = 0 | | strcasecmp ($SUBSTR, '. jpeg ') = 0 | | str CASECMP ($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 name for later generation of complex new filename $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 up the picture upload path, put in the upload folder, to the month and day to generate folder category storage,//rtrim (Base_url (), '/') in factis the root directory of the site, we handle $path = RTrim (Base_url (), '/'). '/upload/'. Date (' Ymd ').
   '/';
   Ensure the catalogue can be written ensure_writable_dir ($path);
   FileName $name = "$md 5.0x{$rawImageWidth}x{$rawImageHeight} {$extension}"; Add picture file does not change to, 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; Picture upload Success Logo $files [$index] [' width '] = $rawImageWidth; Picture width $files [$index] [' height '] = $rawImageHeight; Picture height $success + +;
   Success +1}//The picture has been JSON returned to the JS processing page, where everyone can change to their own JSON return processing code echo json_encode (' Total ' => count ($files),
 ' Success ' => $success, ' Files ' => $files,)); }/********************************* split *************************************************///Here I enclose ensure_writable _dir () function code/** * Ensure folder exists and can be written * * @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");

 }
 }
}

Code basically added a comment, easy to understand, although it is to use PHP processing picture upload, but you understand the upload process code to deal with the logic of thinking, will be used in. NET or Java can be.

The above is the use of jquery plug-ins ajaxfileupload asynchronous upload files of the whole process of analysis, I hope to help you learn.

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.