HTML5 File Upload Example
EDITORIAL NOTE: In this post, we feature a comprehensive HTML5 File Upload Example.
Today I’ll explain how to use HTML 5, to read information about file(s) selected by users, and to upload the file(s) on a server.
The FileApi is one of the most interesting features added with HTML 5. Now we can display file(s) information before they are uploaded on the server, and we can send them without “posting” a form.
We’ll see how to access file(s) information when they are selected by users, and then upload them asynchronously using an Ajax Request.
1. Show File(s) information
1.1 : A single file
Access information of a single file selected by the user.
Here is the HTML code :
<input type="file" id="fileinput" />
When the user choose a file, the “change“ event is fired on the input element, so we can listen for it :
document.getElementById('fileinput').addEventListener('change', function(){ var file = this.files[0]; // This code is only for demo ... console.log("name : " + file.name); console.log("size : " + file.size); console.log("type : " + file.type); console.log("date : " + file.lastModified); }, false);
As you can see, the FileApi is quite simple to use, it adds the “files” property on the HTMLInputElement.
Note : The “files” property is not writable, you can only read its content.
As you may have noticed, we retrieved the chosen file, by accessing the index 0 of the FileList collection : this.files[0]
.
1.2 Multiple files
Now we’ll display information about all the files selected by the user.
Here is the HTML code :
<input type="file" id="fileinput" multiple="multiple" />
We’ve just added the multiple="multiple"
attribute to the HTML element, this will allow user to choose multiple files to upload.
document.getElementById('fileinput').addEventListener('change', function(){ for(var i = 0; i<this.files.length; i++){ var file = this.files[i]; // This code is only for demo ... console.group("File "+i); console.log("name : " + file.name); console.log("size : " + file.size); console.log("type : " + file.type); console.log("date : " + file.lastModified); console.groupEnd(); } }, false);
Note : you can filter elements by adding the “accept” attribute to the input element :
For example, if you only want your user to upload some images, you can filter on the “image/*” mime-type :
<input type="file" id="fileinput" multiple="multiple" accept="image/*" />
1.3 Previewing Files
As we can read the file(s) information, we can also read the content of the file, this, for example, can allow us to preview selected files before upload.
Let’s see an example with previewing images.
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Preview images</title> <style> #gallery .thumbnail{ width:150px; height: 150px; float:left; margin:2px; } #gallery .thumbnail img{ width:150px; height: 150px; } </style> </head> <body> <h2>Upload images ...</h2> <input type="file" id="fileinput" multiple="multiple" accept="image/*" /> <div id="gallery"></div> <script src="gallery.js"></script> </body> </html>
The JavaScript code to manage the uploaded files :
gallery.js
var uploadfiles = document.querySelector('#fileinput'); uploadfiles.addEventListener('change', function () { var files = this.files; for(var i=0; i<files.length; i++){ previewImage(this.files[i]); } }, false);
And, the previewImage
function that will display the image(s) selected by the user.
gallery.js
function previewImage(file) { var galleryId = "gallery"; var gallery = document.getElementById(galleryId); var imageType = /image.*/; if (!file.type.match(imageType)) { throw "File Type must be an image"; } var thumb = document.createElement("div"); thumb.classList.add('thumbnail'); // Add the class thumbnail to the created div var img = document.createElement("img"); img.file = file; thumb.appendChild(img); gallery.appendChild(thumb); // Using FileReader to display the image content var reader = new FileReader(); reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img); reader.readAsDataURL(file); }
Here we introduced the FileReader
object, that allow us to asynchronously read the contents of files.
Instantiate the object with the new FileReader()
, then tell the object to read the data from the file with the method readAsUrl
.
The onload
method is called after the content is read by the object like an event, then the content of the file is assigned to the image src attribute: aImg.src = e.target.result;
2. Upload The files
Now we will upload files using XMLHttpRequest (Ajax).
For each files selected by the user we will create an HTTP request to send the file to the server.
First create a function to upload a file using XMLHttpRequest :
function uploadFile(file){ var url = 'server/index.php'; var xhr = new XMLHttpRequest(); var fd = new FormData(); xhr.open("POST", url, true); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { // Every thing ok, file uploaded console.log(xhr.responseText); // handle response. } }; fd.append("upload_file", file); xhr.send(fd); }
This function will create an ajax request (POST) on the url and send the file in the “upload_file” request parameter (we may access this parameter with the $_FILES['upload_file']
variable.
Now we’ll connect the uploadFile
function to the javascript that manage the selected files :
The HTML:
<input type="file" id="uploadfiles" multiple="multiple" />
The JavaScript:
var uploadfiles = document.querySelector('#uploadfiles'); uploadfiles.addEventListener('change', function () { var files = this.files; for(var i=0; i<files.length; i++){ uploadFile(this.files[i]); // call the function to upload the file } }, false);
And the PHP script:
if (isset($_FILES['upload_file'])) { if(move_uploaded_file($_FILES['upload_file']['tmp_name'], "datas/" . $_FILES['upload_file']['name'])){ echo $_FILES['upload_file']['name']. " OK"; } else { echo $_FILES['upload_file']['name']. " KO"; } exit; } else { echo "No files uploaded ..."; }
3. Download
I hope this little example will help you to use HTML5 Apis to upload files.
You can download the full source code of this example here : HTML5 File Upload Example
Thanks. I was confused about the identity of File API, since something called FileSystem API, which is derived from File API, apparently will not be supported by browsers other than Chrome.
I love the preview window and can get that working fine off the files downloaded but I can’t get the upload bit to work. In your demo there is no option to upload either. The XMLHttpRequest (Ajax) doesn’t look to be anywhere in the files…where would this go? Sorry I’m a pretty new to this and really want this to work but struggling. Do you have a ‘complete example’ set of files?
Sorry should have said. I can get it working to upload 1 file but not mulitiple. On submit of the form I link to another php file which uploads the file, but I really want to be able to upload multiple files.
Thanks this is an awesome article. Very handy to be able to accept only certain file types before uploading.
How do you actually upload files? I have lighttpd and php7 setup but I can only select files. I don’t get an upload button at all.
Great article
Thanks, You saved us.. Great article.
Very helpful article thanks alot. Please how to create dbase for storing customers and retrieve it?
Thanks.Awesome!! Very Clear!!
thanks, this is the only work version for simple ajax uploading. Please add datas sub-folder, otherwise it will fail to upload.
thanks again
Fine way of explaining, and pleasant post to get
facts about my presentation subject matter, which i am going
to present in college.
Cool article