Advertisement
Guest User

Untitled

a guest
May 20th, 2012
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  *  File Upload Progress JavaScript Class version 0.1
  3.  *  Copyright (C) 2010 Hoppinger BV
  4.  *  www.hoppinger.com
  5.  *
  6.  *  This program is free software: you can redistribute it and/or modify
  7.  *  it under the terms of the GNU Lesser General Public License as published by
  8.  *  the Free Software Foundation, either version 3 of the License, or
  9.  *  (at your option) any later version. See <http://www.gnu.org/licenses/>.
  10. **/
  11.  
  12.  
  13.  
  14. /**
  15.  *
  16.  * uploadProgress class which add's a progress bar to file uploads
  17.  * The contents of $_FILES ends JSON'ed in $_POST with same name as original type=file
  18.  *
  19.  * @author Korstiaan de Ridder korstiaan@hoppinger.com
  20.  * @version 27-05-2010 0.1
  21. **/
  22.  
  23. var uploadProgress = new Class({
  24.  
  25.     Implements: [Options],
  26.     options:
  27.     {
  28.         i_interval : 1000,
  29.         s_actionHelper : 'progress.php',
  30.         messages:  
  31.             {
  32.                 upload_limit_reached : 'Upload size limit reached'
  33.             }
  34.     },
  35.  
  36.     s_uniqueId : '',
  37.     o_form : {},
  38.     a_inputs : [],
  39.     s_action : '',
  40.     s_target : '',
  41.     o_elements : {},
  42.     initialize : function(o_form,o_options)
  43.     {
  44.         this.setOptions(o_options);
  45.  
  46.         this.o_form = o_form;
  47.  
  48.         // Save original values of attributes we're gonna change
  49.         this.s_action = o_form.get('action');
  50.         this.s_target = o_form.get('target');
  51.  
  52.  
  53.         // Generate a unique id
  54.         this.s_uniqueId = (Math.random()*100000000).toInt();
  55.  
  56.  
  57.         // If form doesn't have id set it
  58.         if(!this.o_form.get('id'))
  59.         {
  60.             this.o_form.set('id','i' + this.s_uniqueId);
  61.         }
  62.  
  63.         // And finally make sure a submit goes through this class
  64.         o_form.addEvent('submit',this.handleSubmit.bind(this));
  65.  
  66.     },
  67.     initializeInputs : function()
  68.     {
  69.         this.o_form.getElements('input[type=file]').each((function(o_input)
  70.             {
  71.                 if(!o_input.isHidden() && o_input.value != '')
  72.                 {
  73.                     this.a_inputs.include(o_input);
  74.                 }
  75.             }).bind(this));
  76.     },
  77.     hideInputs : function()
  78.     {  
  79.         this.a_inputs.each(function(o_input)
  80.         {
  81.             // Arrays in names are evil, so escape them and save the original
  82.             o_input.origName = o_input.get('name');
  83.             o_input.set('name',escape(o_input.get('name')));
  84.             o_input.setStyle('display','none');
  85.         });
  86.     },
  87.     showInputs : function()
  88.     {
  89.         this.a_inputs.each(function(o_input)
  90.         {  
  91.             o_input.set('name',o_input.origName);
  92.             o_input.setStyle('display','block');
  93.         });
  94.     },
  95.     disableButtons : function()
  96.     {
  97.         this.changeButtonsStatus(true);
  98.     },
  99.     enableButtons : function()
  100.     {
  101.         this.changeButtonsStatus(false);
  102.     },
  103.     changeButtonsStatus : function(s_type)
  104.     {
  105.         this.o_form.getElements('input[type=submit]').each((function(o_submit)
  106.         {
  107.             o_submit.set('disabled',s_type);
  108.  
  109.         }).bind(this));
  110.     },
  111.     handleSubmit : function()
  112.     {
  113.         this.initializeInputs();
  114.  
  115.         // Only do something when there are visible input type = file
  116.         if(this.a_inputs.length > 0)
  117.         {
  118.  
  119.             // Initialize the iframe to post to
  120.             var s_targetIframeId = this.o_form.get('id') + '_iframe';
  121.             this.o_elements.o_targetIframe = new IFrame({'id': s_targetIframeId,'name':s_targetIframeId,'styles': {'display': 'none'}}).inject(this.o_form,'after');
  122.  
  123.  
  124.             // Initialize the hidden input field with the upload progress id. Should be on top of the input list!
  125.             this.o_elements.o_apcInput = new Element('input',{'type': 'hidden','name':'APC_UPLOAD_PROGRESS','value':this.s_uniqueId}).inject(this.o_form,'top');
  126.  
  127.             // Set the temporary action and target
  128.  
  129.             this.o_form.set('action',this.options.s_actionHelper);
  130.             this.o_form.set('target',this.o_elements.o_targetIframe.get('id'));
  131.  
  132.             // Disable submit buttons
  133.             this.disableButtons(); 
  134.             // Initialize the progressbar div
  135.             this.o_elements.o_progressBarContainer = new Element('div',{'class':'progressBarContainer'}).inject(this.a_inputs[0],'after');
  136.             this.o_elements.o_progressBarContainer.o_progressText = new Element('span',{'class' : 'progressText'}).inject(this.o_elements.o_progressBarContainer);
  137.             this.o_elements.o_progressBarContainer.o_progressBar = new Element('div',{'class':'progressBar'}).inject(this.o_elements.o_progressBarContainer);
  138.  
  139.  
  140.             // Add some nice fx
  141.             this.o_elements.o_progressBarContainer.o_progressBar.fx = new Fx.Tween(this.o_elements.o_progressBarContainer.o_progressBar);
  142.             this.changeProgress();
  143.  
  144.  
  145.             // And hide the input type = file
  146.             this.hideInputs();
  147.  
  148.             this.i_startTime = (new Date()).getTime();
  149.  
  150.             // Poll it every i_interval milliseconds
  151.             this.periodical = (this.handleProgressRequest.bind(this)).periodical(this.options.i_interval);
  152.         }
  153.     },
  154.     handleProgressRequest : function()
  155.     {
  156.         // Poll the progress by requesting the below url with the generated unique id (APC_UPLOAD_PROGRESS) as parameter
  157.  
  158.  
  159.         new Request.JSON({
  160.                 url : this.options.s_actionHelper,
  161.                 method : 'get',
  162.                 noCache : 'true',
  163.                 onSuccess : (function(o_data)
  164.                 {          
  165.  
  166.  
  167.  
  168.                     // Place the progressbar at the same place as the input of the current file
  169.                     this.a_inputs.each((function(o_input)
  170.                         {
  171.                             var s_name = o_input.get('name');
  172.                             if(o_data.name == s_name)
  173.                             {
  174.                                 this.o_elements.o_progressBarContainer.inject(o_input,'after');
  175.                             }
  176.                         }).bind(this));
  177.                     // If an error has been detected on the server, revert everything and do something with the error
  178.                     if(o_data.error)
  179.                     {
  180.                         this.handleError(o_data.error);
  181.                         this.revertSubmit();
  182.                     }
  183.                     else
  184.                     {  
  185.                         this.changeProgress(o_data);
  186.                         if(o_data.done == 1)
  187.                         {
  188.                             // We're done, so we can finish
  189.                             this.postUpload(o_data);
  190.                         }
  191.                     }
  192.                 }).bind(this)
  193.             }).get({'p':this.s_uniqueId});
  194.     },
  195.     handleError : function(i_error)
  196.     {
  197.  
  198.         if(i_error == 1)
  199.         {
  200.             alert(this.options.messages.upload_limit_reached);
  201.         }
  202.  
  203.  
  204.     },
  205.     postUpload : function(o_data)
  206.     {
  207.         // Loop through every input and set json response in hidden input
  208.         this.a_inputs.each((function(o_input)
  209.             {
  210.                 var s_name = o_input.get('name');
  211.                 var s_value = '';
  212.  
  213.                 if(o_file = o_data.files[s_name])
  214.                 {
  215.                     s_value = JSON.encode(o_file);
  216.                 }
  217.  
  218.  
  219.                 var o_jsonInput = new Element('input',{'type': 'hidden','name':o_input.origName,'value':s_value}).replaces(o_input);
  220.  
  221.  
  222.             }).bind(this));
  223.  
  224.         // Make form "original" again by purging elements and resetting attributes
  225.         this.revertSubmit();
  226.         this.o_form.submit();
  227.     },
  228.     revertSubmit : function()
  229.     {
  230.         // Clear timer if present
  231.         $clear(this.periodical);
  232.  
  233.         // Set attributes to original values
  234.         this.o_form.set('target',this.s_target);
  235.         this.o_form.set('action',this.s_action);
  236.  
  237.         // Purge useless elements
  238.         for(s_element in this.o_elements)
  239.         {
  240.             this.o_elements[s_element].dispose();
  241.         }
  242.  
  243.         // Show the inputs again
  244.         this.showInputs();
  245.  
  246.         // And enable the submits
  247.         this.enableButtons();
  248.     },
  249.  
  250.     changeProgress : function(o_data)
  251.     {
  252.         var f_percentage = 0;
  253.         var i_eta = 0;
  254.                 var eta_return = 0;
  255.         if(o_data && o_data.total && o_data.current)
  256.         {
  257.             var i_curTime = (new Date()).getTime();
  258.             // Calculate percentage and change progressbar
  259.             var i_total = o_data.total;
  260.             var i_current = o_data.current;
  261.  
  262.             var f_rate = (o_data.current / ((i_curTime - this.i_startTime) / 1000)); // bytes per seconds
  263.             var i_eta = ((o_data.total - o_data.current) / f_rate).toInt();
  264.  
  265.             var f_percentage = (i_current / i_total) * 100;
  266.             // Change the progressbars width with some nice fx
  267.         }
  268.         var i_width = ((f_percentage / 100) * this.o_elements.o_progressBarContainer.getStyle('width').toInt()).toInt();
  269.         if(i_width == 0)
  270.         {
  271.             i_width = 1;
  272.         }
  273.         this.o_elements.o_progressBarContainer.o_progressBar.fx.start('width',this.o_elements.o_progressBarContainer.o_progressBar.getStyle('width').toInt(),i_width);
  274.                 if(i_eta >= 3600) { //hour
  275.                     eta_return = i_eta/3600;
  276.                     eta_return = Math.round(eta_return*10)/10 + "hour(s)";
  277.                 } else if(i_eta >= 60) { //minute
  278.                     eta_return = i_eta/60;
  279.                     eta_return = Math.round(eta_return*10)/10 + "min(s)";
  280.                 } else {
  281.                     eta_return = i_eta + "s";
  282.                 }
  283.         this.o_elements.o_progressBarContainer.o_progressText.set('text',(f_percentage).toInt() + '%, eta ' + eta_return);
  284.         this.o_elements.o_progressBarContainer.setStyle('display','block');
  285.     }
  286. });
  287. Element.implement({ isHidden: function(){   var w = this.offsetWidth, h = this.offsetHeight,  force = (this.tagName === 'TR');    return (w===0 && h===0 && !force) ? true : (w!==0 && h!==0 && !force) ? false : this.getStyle('display') === 'none';  },  isVisible: function(){    return !this.isHidden();  }});
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement