phoenixinsilico

Untitled

Nov 25th, 2013
164
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //main.js
  2.  
  3. $(function () {
  4.     'use strict';
  5.  
  6.     // Initialize the jQuery File Upload widget:
  7.     $('#fileupload').fileupload({
  8.         // Uncomment the following to send cross-domain cookies:
  9.         //xhrFields: {withCredentials: true},
  10.         //url: 'server/php/'
  11.     });
  12.  
  13.     // Enable iframe cross-domain access via redirect option:
  14.     $('#fileupload').fileupload(
  15.         'option',
  16.         'redirect',
  17.         window.location.href.replace(
  18.             /\/[^\/]*$/,
  19.             '/cors/result.html?%s'
  20.         )
  21.     );
  22.  
  23.     if (window.location.hostname === 'blueimp.github.io') {
  24.         // Demo settings:
  25.         $('#fileupload').fileupload('option', {
  26.             url: '//jquery-file-upload.appspot.com/',
  27.             // Enable image resizing, except for Android and Opera,
  28.             // which actually support image resizing, but fail to
  29.             // send Blob objects via XHR requests:
  30.             disableImageResize: /Android(?!.*Chrome)|Opera/
  31.                 .test(window.navigator.userAgent),
  32.             maxFileSize: 5000000,
  33.             acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
  34.         });
  35.         // Upload server status check for browsers with CORS support:
  36.         if ($.support.cors) {
  37.             $.ajax({
  38.                 url: '//jquery-file-upload.appspot.com/',
  39.                 type: 'HEAD'
  40.             }).fail(function () {
  41.                 $('<div class="alert alert-danger"/>')
  42.                     .text('Upload server currently unavailable - ' +
  43.                             new Date())
  44.                     .appendTo('#fileupload');
  45.             });
  46.         }
  47.     } else {
  48.         // Load existing files:
  49.         $('#fileupload').addClass('fileupload-processing');
  50.         $.ajax({
  51.             // Uncomment the following to send cross-domain cookies:
  52.             //xhrFields: {withCredentials: true},
  53.             //url: $('#fileupload').fileupload('option', 'url'),
  54.             url: '//localhost:8000/tracking/view/',
  55.             dataType: 'json',
  56.             context: $('#fileupload')[0]
  57.         }).always(function () {
  58.             $(this).removeClass('fileupload-processing');
  59.         }).done(function (result) {
  60.             $(this).fileupload('option', 'done')
  61.                 .call(this, null, {result: result});
  62.         });
  63.     }
  64.  
  65. });
  66.  
  67.  
  68.  
  69.  
  70. //models.py
  71. class UploadFile(models.Model):
  72.     files = models.FileField(upload_to="multiupload")
  73.     slug = models.SlugField(max_length=50, blank=True)
  74.    
  75.     def __unicode__(self):
  76.         return self.file.name
  77.  
  78.     @models.permalink
  79.     def get_absolute_url(self):
  80.         return ('upload-new', )
  81.  
  82.     def save(self, *args, **kwargs):
  83.         self.slug = self.file.name
  84.         super(UploadFile, self).save(*args, **kwargs)
  85.  
  86.     def delete(self, *args, **kwargs):
  87.         """delete -- Remove to leave file."""
  88.         self.file.delete(False)
  89.         super(UploadFile, self).delete(*args, **kwargs)
  90.  
  91.  
  92.  
  93.  
  94.  
  95. //views.py
  96.  
  97. class UploadFileCreateView(CreateView):
  98.     model = UploadFile
  99.    
  100.     def form_valid(self, form):
  101.         self.object = form.save()
  102.         files = [serialize(self.object)]
  103.         data = {'files': files}
  104.         response = JSONResponse(data, mimetype=response_mimetype(self.request))
  105.         response['Content-Disposition'] = 'inline; filename=files.json'
  106.         return response
  107. class BasicPlusVersionCreateView(UploadFileCreateView):
  108.     template_name_suffix = '_basicplus_form'
  109.  
  110. class jQueryVersionCreateView(UploadFileCreateView):
  111.     template_name_suffix = '_jquery_form'
  112.    
  113. class UploadFileDeleteView(DeleteView):
  114.     model = UploadFile
  115.  
  116.     def delete(self, request, *args, **kwargs):
  117.         self.object = self.get_object()
  118.         self.object.delete()
  119.         response = JSONResponse(True, mimetype=response_mimetype(request))
  120.         response['Content-Disposition'] = 'inline; filename=files.json'
  121.         return response
  122.  
  123.  
  124. class UploadFileListView(ListView):
  125.     model = UploadFile
  126.  
  127.     def render_to_response(self, context, **response_kwargs):
  128.         files = [ serialize(p) for p in self.get_queryset() ]
  129.         data = {'files': files}
  130.         response = JSONResponse(data, mimetype=response_mimetype(self.request))
  131.         response['Content-Disposition'] = 'inline; filename=files.json'
  132.         return response
  133.  
  134.  
  135.  
  136.  
  137. //response.py
  138. # encoding: utf-8
  139. from django.http import HttpResponse
  140. from django.utils import simplejson
  141.  
  142. MIMEANY = '*/*'
  143. MIMEJSON = 'application/json'
  144. MIMETEXT = 'text/plain'
  145.  
  146.  
  147. def response_mimetype(request):
  148.     """response_mimetype -- Return a proper response mimetype, accordingly to
  149.    what the client accepts, as available in the `HTTP_ACCEPT` header.
  150.  
  151.    request -- a HttpRequest instance.
  152.  
  153.    """
  154.     can_json = MIMEJSON in request.META['HTTP_ACCEPT']
  155.     can_json |= MIMEANY in request.META['HTTP_ACCEPT']
  156.     return MIMEJSON if can_json else MIMETEXT
  157.  
  158.  
  159. class JSONResponse(HttpResponse):
  160.     """JSONResponse -- Extends HTTPResponse to handle JSON format response.
  161.  
  162.    This response can be used in any view that should return a json stream of
  163.    data.
  164.  
  165.    Usage:
  166.  
  167.        def a_iew(request):
  168.            content = {'key': 'value'}
  169.            return JSONResponse(content, mimetype=response_mimetype(request))
  170.  
  171.    """
  172.     def __init__(self, obj='', json_opts=None, mimetype=MIMEJSON, *args, **kwargs):
  173.         json_opts = json_opts if isinstance(json_opts, dict) else {}
  174.         content = simplejson.dumps(obj, **json_opts)
  175.         super(JSONResponse, self).__init__(content, mimetype, *args, **kwargs)
  176.  
  177.  
  178.  
  179. //serialize.py
  180.  
  181. # encoding: utf-8
  182. import mimetypes
  183. import re
  184. from django.core.urlresolvers import reverse
  185.  
  186.  
  187. def order_name(name):
  188.     """order_name -- Limit a text to 20 chars length, if necessary strips the
  189.    middle of the text and substitute it for an ellipsis.
  190.  
  191.    name -- text to be limited.
  192.  
  193.    """
  194.     name = re.sub(r'^.*/', '', name)
  195.     if len(name) <= 20:
  196.         return name
  197.     return name[:10] + "..." + name[-7:]
  198.  
  199.  
  200. def serialize(instance, file_attr='file'):
  201.     """serialize -- Serialize a Picture instance into a dict.
  202.  
  203.    instance -- Picture instance
  204.    file_attr -- attribute name that contains the FileField or ImageField
  205.  
  206.    """
  207.     obj = getattr(instance, file_attr)
  208.     return {
  209.         'url': obj.url,
  210.         'name': order_name(obj.name),
  211.         'type': mimetypes.guess_type(obj.path)[0] or 'image/png',
  212.         'thumbnailUrl': obj.url,
  213.         'size': obj.size,
  214.         'deleteUrl': reverse('upload-delete', args=[instance.pk]),
  215.         'deleteType': 'DELETE',
  216.     }
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×