Halaman

Kamis, 05 Juni 2014

[Javascript] Uploading File Field using AJAX

This simple snippet will show you how to upload file through the AJAX `protocol` using pure Javascript
<form id="form" method="post" action="" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" name="submit" value="submit"/>
</form>

<script>
 var form = document.getElementById('form');
 
 form.onsubmit = function(a){
  //get the file we would likt to submit
  var theFile = form.elements.namedItem("file").files[0];
  
  if(theFile != undefined){
   var xhr = new XMLHttpRequest(); 
   
   //monitor the on upload data progress (so we could implement the simple progress bar perhaps..?)
   xhr.upload.addEventListener("progress", function(e){ 
    console.log(e);
   }, false);
   
   //POST method with the target url of 'test.php'
   xhr.open( "POST" , "test.php");  
   
   var ff= new FormData();
   //append any post data here
   ff.append( "submit" , 1 );
   //append the file here
   ff.append( "file" , theFile );
   //finally send the ajax request!
   xhr.send(ff);
  }
  
  return false;
 }
</script>