2 * jquery.uploadProgress
4 * Copyright (c) 2008 Piotr Sarnacki (drogomir.com)
6 * Licensed under the MIT license:
7 * http://www.opensource.org/licenses/mit-license.php
11 $.fn.uploadProgress = function(options) {
15 progressBar: "#progressbar",
16 progressUrl: "/progress",
18 uploading: function() {},
19 complete: function() {},
20 success: function() {},
23 uploadProgressPath: '/javascripts/jquery.uploadProgress.js',
24 jqueryPath: '/javascripts/jquery.js',
30 for(var i = 0; i<options.preloadImages.length; i++)
32 options.preloadImages[i] = $("<img>").attr("src", options.preloadImages[i]);
34 /* tried to add iframe after submit (to not always load it) but it won't work.
35 safari can't get scripts properly while submitting files */
36 if($.browser.safari && top.document == document) {
37 /* iframe to send ajax requests in safari
38 thanks to Michele Finotto for idea */
39 iframe = document.createElement('iframe');
40 iframe.name = "progressFrame";
41 $(iframe).css({width: '0', height: '0', position: 'absolute', top: '-3000px'});
42 document.body.appendChild(iframe);
44 var d = iframe.contentWindow.document;
46 /* weird - safari won't load scripts without this lines... */
47 d.write('<html><head></head><body></body></html>');
51 var s = d.createElement('script');
52 s.src = options.jqueryPath;
53 /* must be sure that jquery is loaded */
54 s.onload = function() {
55 var s1 = d.createElement('script');
56 s1.src = options.uploadProgressPath;
63 return this.each(function(){
64 $(this).bind('submit', function() {
66 for (i = 0; i < 32; i++) { uuid += Math.floor(Math.random() * 16).toString(16); }
73 /* patch the form-action tag to include the progress-id if X-Progress-ID has been already added just replace it */
74 if(old_id = /X-Progress-ID=([^&]+)/.exec($(this).attr("action"))) {
75 var action = $(this).attr("action").replace(old_id[1], uuid);
76 $(this).attr("action", action);
78 $(this).attr("action", jQuery(this).attr("action") + "?X-Progress-ID=" + uuid);
80 var uploadProgress = $.browser.safari ? progressFrame.jQuery.uploadProgress : jQuery.uploadProgress;
81 options.timer = window.setInterval(function() { uploadProgress(this, options) }, options.interval);
86 jQuery.uploadProgress = function(e, options) {
89 url: options.progressUrl + "?X-Progress-ID=" + options.uuid,
90 dataType: options.dataType,
91 success: function(upload) {
92 if (upload.state == 'uploading') {
93 upload.percents = Math.floor((upload.received / upload.size)*1000)/10;
95 var bar = $.browser.safari ? $(options.progressBar, parent.document) : $(options.progressBar);
96 bar.css({width: upload.percents+'%'});
97 options.uploading(upload);
100 if (upload.state == 'done' || upload.state == 'error') {
101 window.clearTimeout(options.timer);
102 options.complete(upload);
105 if (upload.state == 'done') {
106 options.success(upload);
109 if (upload.state == 'error') {
110 options.error(upload);