Web Development with jQuery®

(Elliott) #1

Implementing Drag-and-Drop File Uploads (^) ❘ 315
Check for the existence of the FormData object to see if a more recent revision of drag-and-drop
upload is supported by your browser. The FormData object is provided by the browser and facilitates
the creation of the HTTP request that will ultimately pass the uploaded fi le data across the Internet.
In this example, the FormData object creates a POST request with encoding multipart/form-data. In
a traditional fi le upload, you would have to add multipart/form-data to the

element in the
enctype attribute. The FormData object takes care of this for you automatically.
if (typeof FormData !== 'undefined')
{
var form = new FormData();
// The form object invoked here is a built-in object, provided
// by the browser; it allows you to specify POST variables
// in the request for the file upload.
You can append arguments to the FormData object by using the append() method. The fi rst argument
appended is the path argument. This creates a POST variable called path on the server side and sig-
nals to the server-side script where you want to upload the fi les.
form.append('path', this.path);
Each fi le is iterated by passing the this.files array to the each() method. The fi le is passed to the
server side in a file[] array. The square brackets are used by PHP to signal the creation of an array.
The syntax used to do this might be different in your server-side language of choice. Some addi-
tional information is passed on to the server in a name[] variable and the replaceFile[] variable.
You can create as many variables as you need.
$(this.files).each(
function(key, file)
{
form.append('file[]', file);
form.append('name[]', file.name);
form.append('replaceFile[]', 1);
}
);
Finally, the entire POST request including the uploaded fi le data is sent on to the server-side script
for processing. file/upload.json provides a canned JSON response in the absence of a real server-
side script.
// This sends a POST request to the server at the path
// /file/upload.php. This is the server-side file that will
// handle the file upload.
this.http.open('POST', 'file/upload.json');
this.http.send(form);
}
If your browser does not support the FormData object, you print a message to the JavaScript console
and close the progress dialogue.
else
{
http://www.it-ebooks.info

Free download pdf