Ticket #4165: 5116_progress_bar_newforms_admin.2.diff

File 5116_progress_bar_newforms_admin.2.diff, 7.6 KB (added by Michael Axiak <axiak@…>, 8 years ago)

Reworked a lot of JS, this is for newforms-admin.

  • django/contrib/admin/media/js/UploadProgress.js

     
     1
     2var upload_progress_failures = 0;
     3var TOTAL_UPLOAD_PROGRESS_FAILURES = 10;
     4
     5function getxy(){
     6    var x,y;
     7    if (self.innerHeight) // all except Explorer
     8        {
     9        x = self.innerWidth;
     10        y = self.innerHeight;
     11        }
     12    else if (document.documentElement && document.documentElement.clientHeight)
     13        // Explorer 6 Strict Mode
     14        {
     15        x = document.documentElement.clientWidth;
     16        y = document.documentElement.clientHeight;
     17        }
     18    else if (document.body) // other Explorers
     19        {
     20        x = document.body.clientWidth;
     21        y = document.body.clientHeight;
     22        }
     23    return {'x':x,'y':y}
     24    }
     25
     26
     27function upload_ajax_problem() {
     28    /* If there's a problem, will cancel after
     29       TOTAL_UPLOAD_PROGRESS_FAILURES tries.   */
     30
     31    progress_wrap = document.getElementById('progress_wrap');
     32    upload_progress_failures++;
     33    if (upload_progress_failures >= TOTAL_UPLOAD_PROGRESS_FAILURES){
     34      window.clearTimeout(interval);
     35    }
     36    progress_wrap.style.visibility = 'hidden';
     37}
     38
     39var humanvalue = ['B','KB','MB','GB']
     40function humanize(bytes) {
     41  curbytes = bytes;
     42  iterations = 0;
     43  while (curbytes>1024) {
     44    iterations++;
     45    curbytes=curbytes/1024;
     46  }
     47  return curbytes.toFixed(1) + ' ' + humanvalue[iterations];
     48}
     49
     50interval = null;
     51function fetch(uuid) {
     52  /* no ajax here */
     53  if (!xmlhttp) {
     54    upload_ajax_problem();
     55    return;
     56  }
     57
     58  req = xmlhttp;
     59  req.open("GET", "/admin/upload_progress/", true);
     60  req.onreadystatechange = function () {
     61    if (req.readyState == 4) {
     62      try {
     63        request_status = req.status;
     64      } catch (e) {
     65        /* Really bad. */
     66        request_status = -1;
     67      }
     68      if (request_status == 200) {
     69        var upload = new Function(" return "+req.responseText)();
     70        if (upload) {
     71          progress_wrap = document.getElementById('progress_wrap');
     72
     73          if (!upload.state) {
     74            progress_wrap.style.visibility = 'hidden';
     75            return
     76          } else if (upload.state == 'done') {
     77             window.clearTimeout(interval);
     78             progress_wrap.style.visibility = 'hidden';
     79             return;   
     80          } else {
     81             progress_bar = document.getElementById('progress_bar');
     82             bar_txt = document.getElementById('progress_text');
     83
     84             progress_wrap.style.visibility = 'visible';
     85             bar_txt.innerHTML = ((upload.received / upload.size) * 100).toFixed(1)
     86                     + '% - ' + humanize(upload.received) + ' of '
     87                     + humanize(upload.size);
     88             bar_width__px = 400 * upload.received / upload.size;
     89             progress_bar.style.width = bar_width__px + 'px';
     90          }
     91        } else {
     92          upload_ajax_problem();
     93        }
     94      } else {
     95        upload_ajax_problem();
     96      }
     97    }
     98  };
     99  try {
     100    req.setRequestHeader("X-Progress-Id", uuid);
     101  } catch (e) {
     102    /* couldn't set the header, the request is broken. */
     103    req.abort();
     104  }
     105  req.send(null);
     106
     107}
     108
     109
     110function openprogress(e) {
     111    upload_progress_failures = 0;
     112    uuid = "";
     113    for (i = 0; i < 32; i++) {
     114        uuid += Math.floor(Math.random() * 16).toString(16);
     115        }
     116    frm = e.target||e.srcElement;
     117
     118    if (frm.action.indexOf('?') == -1) {
     119       frm.action=frm.action+"?progress_id=" + uuid;
     120    } else {
     121       frm.action=frm.action+"&progress_id=" + uuid;
     122    }
     123
     124    if (document.getElementById('progress_wrap')) {
     125        document.getElementById('progress_wrap').style.visibility = 'hidden';
     126        document.getElementById('progress_bar').style.width = '0';
     127        document.getElementById('progress_text').innerHTML = '0%';
     128
     129        interval = window.setInterval(
     130        function () {
     131            fetch(uuid);
     132            },
     133        1000
     134        );
     135        return;
     136    }
     137
     138    pos = getxy()
     139    posx = parseInt((pos.x/2)-(420/2), 10)
     140    posy = parseInt((pos.y/2)-(50/2), 10)
     141
     142    progress_wrap = quickElement('div', document.body, '', 'style',
     143        'position: absolute; top: '+posy+'px; left: '+posx+'px; height: 50px; ' +
     144        'padding: 10px; width: 420px; background: #ffffff; ' +
     145        'border: solid 1px #dddddd;' +
     146        'visibility: hidden;', 'id', 'progress_wrap')
     147
     148    progress_label = quickElement('h1', progress_wrap, 'Upload progress')
     149
     150    progress = quickElement('div', progress_wrap, '', 'style',
     151        'top: 0; left: 0; width: 0px; ', 'id', 'progress_bar', 'class', 'submit-row')
     152
     153    progress_text = quickElement('div', progress_wrap, '0%', 'style',
     154        'color: #000000; ', 'id', 'progress_text')
     155    progress_wrap.style.visibility = 'hidden';
     156    interval = window.setInterval(
     157        function () {
     158            fetch(uuid);
     159            },
     160        1000
     161        );
     162    }
     163
     164addEvent(window, 'load', function() {
     165        frms = document.getElementsByTagName('form');
     166        for (var i=0; i<frms.length; i++) {
     167           if (frms[i].encoding.toLowerCase() == 'multipart/form-data') {
     168              addEvent(frms[i], 'submit',  openprogress);
     169              return;
     170           }
     171        }
     172    });
  • django/contrib/admin/options.py

     
    154154        js = ['js/core.js', 'js/admin/RelatedObjectLookups.js']
    155155        if self.prepopulated_fields:
    156156            js.append('js/urlify.js')
     157        if self.opts.has_field_type(models.FileField):
     158            js.append('js/UploadProgress.js')
    157159        if self.opts.has_field_type(models.DateTimeField) or self.opts.has_field_type(models.TimeField) or self.opts.has_field_type(models.DateField):
    158160            js.extend(['js/calendar.js', 'js/admin/DateTimeShortcuts.js'])
    159161        if self.opts.get_ordered_objects():
  • django/contrib/admin/urls.py

     
    99    #('^password_change/done/$', 'django.contrib.auth.views.password_change_done'),
    1010    ('^template_validator/$', 'django.contrib.admin.views.template.template_validator'),
    1111
     12    # Upload progress bar support
     13    #('^upload_progress/$', 'django.contrib.admin.views.main.upload_progress'),
    1214    # "Add user" -- a special-case view
    1315    ('^auth/user/add/$', 'django.contrib.admin.views.auth.user_add_stage'),
    1416    # "Change user password" -- another special-case view
  • django/contrib/admin/views/main.py

     
    4848            res[i] = '_%02X' % ord(c)
    4949    return ''.join(res)
    5050
     51def upload_progress(request):
     52    """
     53    Given this request, returns a JSON
     54    object that has information on a file upload progress.
     55    If there is no file upload in progress, returns an
     56    empty dictionary, '{}'.
     57    """
     58
     59    from django.utils import simplejson
     60
     61    content = simplejson.dumps(request.file_progress)
     62
     63    return HttpResponse(content=content, mimetype='text/plain')
     64
    5165def model_admin_view(request, app_label, model_name, rest_of_url):
    5266    model = models.get_model(app_label, model_name)
    5367    if model is None:
Back to Top