Interview Questions

HTML5 - Ajax File Upload

Use the following code to upload a file through AJAX (POST) in HTML5.

<script>
function uploadFiles(evt) {
 var files = evt.target.files; // FileList object
  var formData = new FormData();
   url = '/server';
  for (var i = 0, file; file = files[i]; ++i) {
    formData.append(file.name, file);
  }
alert("send");
  var xhr = new XMLHttpRequest();
  xhr.open('POST', url, true);
  xhr.onload = function(e) {  };
   alert("send");
  xhr.send(formData);  // multipart/form-data
}

document.getElementById('files').addEventListener('change', uploadFiles, false);
</script>

<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>