HTML and CSS Reference
In-Depth Information
Listing 11-11.
Uploading Files Using the
XMLHttpRequest
Object
var xhr = new XMLHttpRequest();
function UploadFiles() {
var data = new FormData();
for (var i = 0; i < files.length; i++) {
data.append(files[i].name, files[i]);
}
xhr.upload.addEventListener(“progress”, OnProgress, false);
xhr.addEventListener(“load”, OnComplete, false);
xhr.addEventListener(“error”, OnError, false);
xhr.addEventListener(“abort”, OnAbort, false);
xhr.open(“POST”, “UploadHandler.ashx”);
xhr.send(data);
}
This code declares a global
XMLHttpRequest
object (
xhr
). The
UploadFiles()
function first creates a
new
FormData
object. It then iterates through all the files selected by the user. The files collection contains
the
File
objects as selected using the drag-and-drop operation. All the selected files are appended to the
FormData
object using the
FormData
object's
append()
method.
Next, the
addEventListener()
method wires event handlers for the four events:
progress
,
load
,
error
,
and
abort
. Note that because you're interested in tracking the progress of the data-upload operation, the
progress
event of the
upload
object is handled rather than the
progress
event of the
XMLHttpRequest
object.
The event-handler functions
OnProgress()
,
OnComplete()
,
OnError()
, and
OnAbort()
are discussed shortly.
The
XMLHttpRequest
object's
open()
method is then called by specifying
POST
as the request type and
UploadHandler.ashx
as the URL.
UploadHandler.ashx
is an ASP.NET generic handler that saves the
uploaded files on the server. Finally, you call the
XMLHttpRequest
object's
send()
method and pass the
FormData
object to it as a parameter.
The Cancel button calls the
XMLHttpRequest
object's
abort()
method, as shown here:
function CancelUpload() {
xhr.abort();
}
The event-handler functions that handle the
progress
,
load
,
error
, and
abort
events are shown in
Listing 11-12.
Listing 11-12.
Handling Events of the
XMLHttpRequest
Object
function OnProgress(evt) {
if (evt.lengthComputable) {
var progress = Math.round(evt.loaded * 100 / evt.total);
$(“#uploadProgress”).attr(“value”, progress);
}
}
function OnComplete(evt) {
alert(evt.target.responseText);
}
function OnError(evt) {
alert(“Error Uploading File(s)!”);