Add Additional Field to Jquery Blueimp File Upload
HTML5 and Blueimp jQuery-File-Upload Plugin Consequence Handling
Every bit we saw in the Using HTML5 and the Blueimp jQuery-File-Upload Plugin To Upload Large Files article, uploading files in HTML5 is a complex enough undertaking that information technology's worth your while to use a plugin rather than try to write everything yourself. That article provided an overview of how the Blueimp Plugin works and how to reach a minimal setup to become up and running quickly. By dissimilarity, today's follow-upward will be a lot more lawmaking intensive as we'll be writing the event handlers to display file information, image thumbnails, and individual file progress bars.
Creating a Chunked Upload
On the surface, information technology seems pretty easy. You let the user selection a file on their system, intermission it into chunks and make multiple Ajax calls to send the information up to the server. Elementary, except for one thing. Due to the asynchronous nature of both the FileReader and XMLHTTPRequest objects, the chunks are often sent in the wrong social club! That means that you need a server-side process that tin can create temporary files and keep track of the chunks and so that they can be reassembled into the original files. I'd rather non write that code, thanks.
We'll make our phone call to the fileupload widget once the page has finished loading, via the $(document).ready() office. It also includes code to add the remove push's event handler. I renamed the jQuery-File-Upload's index.php file to something more descriptive, merely that is non a necessary pace.
The maxChunkSize tin be set to upload large files in smaller chunks, but note that in guild for chunked uploads to work in Mozilla Firefox, the multipart option has to exist set to false. This is due to the Gecko 2.0 browser engine – used by Firefox 4+ – calculation blobs with an empty filename when building a multipart upload asking using the FormData interface. Moreover, several server-side frameworks, such every bit PHP and Django, also cannot process multipart file uploads with empty filenames.
The fail option sets the callback for jQuery ajax() errors. These should not be confused with JSON responses which contain an error property. Those still count as successful requests even though an error did occur somewhere along the way. We'll see how to bargain with those a little afterward on:
$(document).ready( function() { $('#remove').click(function() { $("#filePreview").find('li').remove(); }); $('#file_upload').fileupload({ url: 'php/upload.php', multipart: fake, fail: part (ev, data) { console.log(ev); } }); });
The Onchange Event Handler
The change option sets the handler for the file input'southward onchange result. We can process individual files using the jQuery $.each() role. The post-obit code creates an unordered list and sets each list item'southward ID to the filename then that we can refer to it later. Note that, for the tape, this is not considered a best do because, according to the W3C spec:
ID tokens must brainstorm with a alphabetic character ([A-Za-z]) and may be followed by any number of letters, digits ([0-nine]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
Each list item contains some file data and a progress bar.
change: part (ev, information) { $.each(data.files, part (index, file) { $("#filePreview").suspend( $('<li>').attr('id', file.proper noun) .suspend($('<h3>').text(file.name)) .append($('<p>') .append('type: ' + (file.blazon || 'unknown')) .suspend($('<br>')) .suspend('size: ' + Math.circular(file.size / 1024) + 'KB' )) .append($('<div>').addClass('loadingIndicator') .append($('<p>').addClass('loader').text('Uploading...')))); }); }
The Onprogress Event Handler
The progress handler option is a good place to provide feedback near an individual file's upload progress. For a global progress handler, apply the progressall option instead.
As I mentioned earlier, we need to refer to the listing item which contains a file'southward loading indicator. The data.files[0] element contains the file information because the progress effect is only ever called for one file. Either data.files[0]['name'] or data.files[0].name volition return the current file name. The li[id='filename'] CSS selector locates the correct list detail. Not surprisingly, the more than standard li['#filename'] doesn't work because it expects the ID to be standards compliant. From there, we can supply the tag name and class ('div.loadingIndicator') to the notice() method to locate the loading indicator <DIV>:
progress: role (ev, data) { if (data.lengthComputable) { var loader = $('li[id="'+data.files[0]['name']+'"]').find('div.loadingIndicator'); var progress = parseInt(data.loaded / data.total * 100, x); loader.css('width', progress + "%"); } }
The Ondone Consequence Handler
One time a file has completed loading, we update the progress indicator and brandish a thumbnail for images. My original test folio had the image preview appearing before the upload, just the jQuery-File-Upload plugin makes that difficult because the FileReader'southward onloadend handler is not bachelor to us and there is no "public" property to my knowledge which contains the file'southward full path. Nevertheless, the response does. Speaking of which, here is what a typical response looks like:
[{"proper noun":"Gnaw.bmp","size":8302,"type":"image\/bmp","url":"http:\/\/localhost\/FileUpload\/blueimp\/php\/files\/Champ.bmp","delete_url":"http:\/\/localhost\/FileUpload\/blueimp\/php\/upload.php?file=Champ.bmp","delete_type":"DELETE"}]
One time we've run it through the json_parse() function, we tin access its attributes but similar any object. The relevant ones to usa are the name, type, and the url. Although at that place were none in the above lawmaking, the presence of the error property tin be tested for and displayed easily plenty:
washed: role (e, data) { var results = json_parse(information.upshot); var fileInfo = results[0]; var li = $('li[id="'+fileInfo['name']+'"]'); var pUploadMessage = li.discover('p.loader'); if (fileInfo['error']) { pUploadMessage.css('color', 'cerise').text("Ajax error encountered: '" + fileInfo['error'] + "'"); } else { if (/prototype\/.*/.test(fileInfo['blazon'])) { var thumb = $('<img>').attr('src', fileInfo['url']); li.prepend(thumb); } li.find('div.loadingIndicator').css('width', '100%').css('backgroundColor', '#0f0'); pUploadMessage.css('color', '#3DD13F').text("Upload complete"); } }
The End Outcome
Multiple file upload with a single file-select control is supported in electric current versions of Firefox, Safari, Opera, and Chrome, merely not Internet Explorer. I did almost of my testing in Firefox nine. Here is a screenshot of an upload of some big video files in that browser. You can encounter the progress indicators in action:
This is what the folio looks like after uploading some images. Notice the thumbnails!
Hither are the files from today's article, not including the blueimp jQuery-File-Upload library and JSON JS parser.
alexanderrismustriog.blogspot.com
Source: https://www.htmlgoodies.com/html5/html5-and-blueimp-jquery-file-upload-plugin-event-handling/
0 Response to "Add Additional Field to Jquery Blueimp File Upload"
Post a Comment