jQuery 透過 AJAX 上傳檔案

上次有一篇提到可以用 plugin 上傳檔案,知道原理其實也可以不用透過 plugin ,最近剛好有一個需求所以就在朋友的幫忙下完成了。

準備簡單的 html 如下:
  1. <input type="file" name="upload_file" id="upload_file">  

然後像這樣處理就可以了
  1. var pic;   
  2. //if select file then upload   
  3. $("#upload_file").on('change', uploadPic);   
  4. function uploadPic(event){   
  5.     //file object   
  6.     pic = event.target.files;   
  7.     var data = new FormData();   
  8.     data.append("upload_file", pic[0]);   
  9.   
  10.     $.ajax({   
  11.             url: 'upload_api',   
  12.             type: 'POST',   
  13.             data: data,   
  14.             cache: false,   
  15.             dataType: 'json',   
  16.             processData: false// Don't process the files   
  17.             contentType: false// Set content type to false as jQuery will tell the server its a query string request   
  18.         success: function(data, textStatus, jqXHR)   
  19.         {   
  20.             console.log(data);   
  21.             
  22.             if(typeof data.error === 'undefined')   
  23.             {   
  24.                 // Success so call function to process the form   
  25.             }   
  26.             else  
  27.             {   
  28.                 // Handle errors here   
  29.                 console.log('ERRORS: ' + data.error);   
  30.             }   
  31.         },   
  32.         error: function(jqXHR, textStatus, errorThrown)   
  33.         {   
  34.             // Handle errors here   
  35.             console.log('ERRORS: ' + textStatus);   
  36.             // STOP LOADING SPINNER   
  37.         }   
  38.     });   
  39.   }  

參考:
Simple File Uploads Using jQuery & AJAX

留言