In previous posts, we showed how to access a file through the input tag or through the Drag and Drop mechanism. In both cases, you can use XMLHttpRequest
to upload the files and follow the upload progress.
Demo
If you’re running the latest beta of Firefox 3.6, check out our file upload demo.
Uploading
XMLHttpRequest
will send a given file to the server as a binary array, so you first need to read the content of the file as a binary string, using the File API. Because both Drag and Drop and the input
tag allow you to handle multiple files at once, you’ll need to create as many requests as there are files.
var reader = new FileReader();
reader.onload = function(e) {
var bin = e.target.result;
// bin is the binaryString
};
reader.readAsBinaryString(file);
Once the file is read, send it to the server with XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open("POST", "upload.php");
xhr.overrideMimeType('text/plain; charset=x-user-defined-binary');
xhr.sendAsBinary(bin);
You can choose to be notified when specific events, such as error, success, or abort, occur during the request (see the MDC documentation for more details).
Following the Upload Progress
The progress
event provides the size of the uploaded portion of the binary content. This allows you to easily compute how much of the file has been uploaded.
Here’s an example showing the percentage of the file that has been uploaded so far:
xhr.upload.addEventListener("progress", function(e) {
if (e.lengthComputable) {
var percentage = Math.round((e.loaded * 100) / e.total);
// do something
}, false);
About Paul Rouget
Paul is a Firefox developer.
27 comments