This is just a quick JavaScript solution if you want pure JS.
var file = document.getElementById('id of your input:file').files[0];
var ajax = new XMLHttpRequest;
var formData = new FormData;
formData.append('imagefile', file);
ajax.upload.addEventListener("progress", myProgressHandler, false);
ajax.addEventListener('load', myOnLoadHandler, false);
ajax.open('POST', 'upload.php', true);
ajax.send(formData);
Note: Some sources say that calling Ajax's open
method should come after creating an object (before any work with ajax
in this case) but me personally never had any troubles using it this way. So it's up to you.
Events:
function myProgressHandler(event) {
//your code to track upload progress
var p = Math.floor(event.loaded/event.total*100);
document.title = p+'%';
}
function myOnLoadHandler(event) {
// your code on finished upload
alert (event.target.responseText);
}
You can also add more event handlers such as "error
" or "abort
". Course, you need to write upload.php
to handle uploaded files (PHP is just an example; there are a lot of examples how to do that on SO).
All you need is to make Ajax call on "change
" event of your input-file element (upper part of code).
In addition, you can write some featuresCheck
function so if user's browser doesn't support something, provide basic file upload instead.
function featuresCheck() {
var res = window.XMLHttpRequest && window.FormData && window.addEventListener;
if (res) return true; else return false;
}
/* and test it in your code */
if (featuresCheck()) {
// use ajax upload
}
else {
// use simple file uploader
}
If you want to use multiple
property of file-input you can't use .files[0]
(first file selected) and you'll need some loop through files list and do separate uploads for each of them (async of course).
Be aware of security. Do double check of uploaded files before you move them from temp location (check MIME type, extension, rename them).