[jQuery] AJAX 上傳檔案 plugin

使用這個 plugin 可以實現 ajax form 上傳檔案的功能,可以讓使用者在上傳檔案的過程不會因為轉頁而影響使用者經驗。


html 部分:
  1. <form action="upload.php" method="post" id="ajaxForm">  
  2. <input type="file" id="pic" name="pic"><br>  
  3. <button id="go_ajs" type="button">上傳</button>  
  4. </form>  
  5. 圖片:   
  6. <br>  
  7. <img src="" id="uploadImg" alt=""  />  
  8. <script>  
  9. // $("#go_ajs").click(ajs_upload);   
  10. // 直接 change 就上傳   
  11. $("#pic").change(ajs_upload);   
  12.   
  13. function ajs_upload(){   
  14.   $("#ajaxForm").ajaxSubmit(   
  15.   {   
  16.   beforeSubmit: function(){},   
  17.   success: function(resp,st,xhr,$form) {   
  18.      if(resp!="err") {   
  19.        $("#uploadImg").attr("src",resp);   
  20.      }   
  21.   }   
  22.   });   
  23. }  

另外在 upload.php 處理上傳的檔案。

  1. $cover = $_FILES["pic"];   
  2.     $fileid"pic_name_".rand(100,999);   
  3.   
  4.     if($cover["error"]>0) {   
  5.         echo "err";   
  6.     }    
  7.     else    
  8.     {   
  9.         // Get the extension name by uploaded filename   
  10.         $extName = substr$cover["name"],strrpos($cover["name"],".") );   
  11.         // check the file type is image   
  12.         $isImage =  getimagesize ($cover["tmp_name"]) ;   
  13.   
  14.         // only jpg or png file name ( or custom by yourself)   
  15.         if($isImage and ($extName==".jpg" or $extName==".png") ) {   
  16.             if( move_uploaded_file($cover["tmp_name"], $fileid.$extName) )   
  17.             {   
  18.                 echo $fileid.$extName;    
  19.                 // print the filename if success   
  20.             } else {   
  21.                 echo "err";   
  22.                 // move upload file failed   
  23.             }   
  24.         } else {   
  25.             echo "err";   
  26.             // err file type   
  27.         }   
  28.     }  

參考: AJAX Upload File 範例,透過 jQuery Form Plugin 上傳檔案或圖片

留言