Refine Post By:

Ever wanted to be able to upload a file without having to navigate away from the page? This article is going to cover the basics of the HTML5 File API as well as take you through a tutorial of it’s usage in hopes to get your feet wet and give you a better understanding on how you can utilize it on your own. To really grasp the concepts of this tutorial, you’re going to need to be familiar with HTML, Javascript, PHP, and AJAX (XMLHttpRequest API).

This example will only work in browsers that support HTML5. If you’re interested in knowing all the browsers that support HTML5, check out this nice Comparison Chart. Generally speaking, Mozilla Firefox 4.0+, Google Chrome 6+ and Safari 5+ all support HTML5. Internet explorer 10+ also supports HTML5.

Why do I need to know Javascript to utilize HTML5?

You don’t…However, to really utilize HTML5 and it’s full potential you do. HTML5 is actually a combination of HTML markup and “pre-built”" Javascript methods and objects. HTML5 relies heavily on user interaction within the DOM (Document Object Model). Unfortunately, the HTML5 File API is one of those things that requires the use of Javascript to accomplish your goals.

Getting Started

Let’s start setting up our basic HTML form that has an input field that allows the user to select a file they wish to upload. You’re going to need to assign an ID to this element so that we have an easy way to reference it and retrieve the data from it with our Javascript method that we’ll create soon. In my example, I assigned the file input field an ID of “upload_file” on line 3.

Additionally I went ahead to include a Javascript “onclick” event listener on line 4 that will call our Javascript method “loadFile()” to handle the file transfer to the server. Also take the time to notice that the upload button isn’t your standard “submit” type and is actually a “button” instead. Since we’re going to dynamically upload the file, the form never needs to be submitted and the user will never have to leave the page.

3
4
5
6
<form action="upload.php" method="post" enctype="multipart/form-data">
    <label>Select a File to Upload</label> <input id="upload_file" type="file" name="upload_file" /> 
    <input type="button" value="Upload" onclick="loadFile()" />
</form>

Great! We got the easy part down. Now it’s time to create our Javascript method(s) to collect the file data and upload it to the server.

HTML5 File API

The HTML5 File API allows developers to open a FileList object containing the File object(s) of an element from the DOM. The file object provides three attributes containing useful information about each file.

  • name – The file’s name as a read-only string. This is just the file name, and does not include any path information
  • size – The size of the file in bytes as a read-only 64-bit integer
  • type – The MIME type of the file as a read-only string, or “” if the type couldn’t be determined

All of this information can be used to create checks and balances. Let’s say you wanted to check to see if a file is too big before the user even tries to upload it. Or maybe you want to limit your users to upload only image files to your server. By using these attribute values, you can create “if statements” that will check the file for things you may require before any actions are invoked. If you don’t understand what a MIME Type is, there’s a list of file extensions in addition to their “MIME” type that they relate to here.

Next, we’re going to create the Javascript method to use the HTML5 File API to handle the collection of the file information and prepare our object for server transfer. Here is a simple method that grabs the FileList object from our referenced DOM element, opens the first File object of the FileList, retrieves the information and finally alerts the information gathered. It than proceeds to call a new function that we will create called “uploadFile()” which will handle the AJAX post method to the server.

function loadFile() {
	// Retrieve the FileList object from the referenced element ID
	var myFileList = document.getElementById('upload_file').files;
 
	// Grab the first File Object from the FileList
	var myFile = myFileList[0];
 
	// Set some variables containing the three attributes of the file
	var myFileName = myFile.name;
	var myFileSize = myFile.size;
	var myFileType = myFile.type;
 
	// Alert the information we just gathered
	alert("FileName: " + myFileName + "- FileSize: " + myFileSize + " - FileType: " + myFileType);
 
	// Let's upload the complete file object
	uploadFile(myFile);
}

Still with me? Good. Now we gathered all the information of our file object from our DOM element and called our uploadFile() method, passing our myFile object to it, which will allow us to create our method to handle the AJAX file upload. If you were interested in creating limitations for your file uploads, you can easily put some “if statements” around the alert and the “uploadFile()” method and check the information we gathered for certain values. But since this is a basic tutorial of the functionality, we’re going to continue forward with the AJAX and using the HTML5 version of XMLHttpRequest.

Uploading with XMLHttpRequest Level 2

The XMLHttpRequest object has gotten a facelift in HTML5. Specifically, it’s called XMLHttpRequest Level 2. With XMLHttpRequest Level 2, we are able to upload and download Files and FormData objects. Additionally, it allows us to add event listeners to the connection, enabling us to track the “progress” of the streaming file upload or download. The new XMLHttpRequest capabilities extend much further than what I just described, and the event listeners are outside the scope of this tutorial. If you are interested in learning about them there is an article that shows you how to use them.

Moving forward! If you read the last paragraph closely, you’re probably wondering about the FormData object. A FormData object is a collection of names and values from the form element. The names of the object coincide with the input element name attribute, and the values obviously contains the input from the user. So when you call the getFormData() method on the form, you’ll get a reference to the FormData object that holds all the data from the form.

What we’re going to do is create a FormData object and append myFileObject (we’re passing it from the previous method) to it so that we can prepare our data to be transferred to the server through our AJAX (XMLHttpRequest) connection. We’re then going to open the connection to our destination, and send the information!

function uploadFile(myFileObject) {
	// Open Our formData Object
	var formData = new FormData();
 
	// Append our file to the formData object
	// Notice the first argument "file" and keep it in mind
	formData.append('my_uploaded_file', myFileObject);
 
	// Create our XMLHttpRequest Object
	var xhr = new XMLHttpRequest();
 
	// Open our connection using the POST method
	xhr.open("POST", 'upload.php');
 
	// Send the file
	xhr.send(formData);
}

Congratulations! You just successfully upload a file to the server. All you have to do from here is create your “upload.php” file to handle the incoming POST request and handle the uploaded file. If you would like to learn more about handling PHP uploaded files, check out the tutorial (PHP File Upload). Basically when you upload a file to the server, by default, the server places the file within a temporary uploads folder. You have to use a PHP script to grab the file from that folder and move it into your desired location.

How do I do this with PHP?

I’m not going to cover in detail how you do this with PHP, but basically what you do is grab the file using the PHP $_FILES array that was created from your AJAX POST. Remember when I said to remember the first argument of the formData(“my_uploaded_file”, myFileObject) method? Well, within your PHP script, the way you reference the uploaded file is by that argument value. For example, within your the PHP array $_FILES['my_uploaded_file'] is all your information about the file that was uploaded. This information includes things like the name, type, size, tmpname and error. In short, all you do is use a PHP method called “move_uploaded_files()” to move the file from the temporary uploads to your target destination. Obviously there are a lot of things you should do within your PHP script to validate the upload but like I said, i’m not going to cover that in detail. I’ve provided an example below of how to use the move_uploaded_file() method.

move_uploaded_file($_FILES['my_uploaded_file'], 'path/to/destination');

Hope this helped! Nobody said it was going to be easy! Anyway, like stated before, this is just the basics for the usage and hopefully you learned enough to keep moving forward. There’s a bunch of things you can do to validate the data that’s being submitted for security purposes in addition to error handling and progress tracking…but that’s for another day!

10 Comments

  1. OK, you’re showing how to use html5 file uploading capabilities, but what you’re not showing is how to figure out whether the browser supports it at all.
    I haven’t been able to find a comprehensive answer to this question anywhere.

  2. Without explaining how to do it in php, you’re beautiful website is useless for my purposes.

  3. Thank you very much!

  4. Is there a way to get a response from the server say via JSON? I want to be able to upload the file and then show it when it’s done.

    Another thing, it doesn’t always upload?

  5. Great work, happy to have stumbled on this blog on blogs list.
    This is the sort of resources that should be shared
    online. You should really look at writing more stuff like this on
    web 2.0 list. It’s a disgrace that search engines aren’t giving wabism.
    com a higher position. If you’re interested, please come and read my web site. Kudos

  6. Thanks! I was having some trouble figuring out how to deal with an ajax file upload in my java servlet. Your example showed me how and it worked perfectly first time. Not production ready yet, but proof of concept and functional prototype were my goals for this sprint.

  7. move_uploaded_file() expects parameter 1 to be string, array given

  8. How to display a message when finished uploading

  9. Magnificent web site. Plenty of useful information here. I am sending it to several pals ans also sharing in delicious. And naturally, thank you in your effort!

Leave a comment