Javascript – AJAX – Uploading a file (HTML 5) & PHP

ajaxhtmljavascriptPHP

I feel completely out of my depth but I feel so close..

I'm trying to Upload a file using AJAX. I found this tutorial http://blog.new-bamboo.co.uk/2010/7/30/html5-powered-ajax-file-uploads and it seemed to be going quite well until the end. I can't seem to access the file in PHP i.e. using $_FILES["foo"]["name"];
and I'm not sure how to upload using other techniques.

I'm not looking for the code to be perfect, just kept simple so I can understand what's going on. Thanks in advance 🙂

Here is my server side code:

HTML:

page title

</head> 
<body>




  <form onsubmit='showUser(); return false;' enctype='multipart/form-data'>
    <input id='the-file' name='file' type='file' />
    <input type='submit'>
  </form>
  <br />


  <div id='txtHint'><b></b></div>

</body>

Javascript:

function showUser(str)
{
var fileInput = document.getElementById('the-file');
var file = fileInput.files[0];
var foo = file.fileName;

if (str=="")
 {
 document.getElementById("txtHint").innerHTML="";
 return;
 } 
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
 xmlhttp=new XMLHttpRequest();
 }
else
 {// code for IE6, IE5
 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
 xmlhttp.onreadystatechange=function()
  {
 if (xmlhttp.readyState==4 && xmlhttp.status==200)
  {
  document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
  }
 }
 xmlhttp.open("POST","new_film_pro.php",true);
 xmlhttp.setRequestHeader("Content-type", "multipart/form-data");
 xmlhttp.setRequestHeader("X-File-Type", file.type);
 xmlhttp.setRequestHeader("X-File-Name", foo);
 xmlhttp.send(file);
 }

PHP:

<?php


$postdata = file_get_contents("php://input");

echo "Name: " . $_SERVER['HTTP_X_FILE_NAME'] . "<br />";

?>

Best Answer

Have a look at http://aquantum-demo.appspot.com/file-upload

Writing straight JavaScript is no longer such a great idea. Using libraries as demonstrated on that page, you can create a much more powerful file upload which supports multiple files, resumeable downloads, progress bar and many other features that you would really have to sweat to implement yourself but which give your user a better experience.