Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //main.js
- $(function () {
- 'use strict';
- // Initialize the jQuery File Upload widget:
- $('#fileupload').fileupload({
- // Uncomment the following to send cross-domain cookies:
- //xhrFields: {withCredentials: true},
- //url: 'server/php/'
- });
- // Enable iframe cross-domain access via redirect option:
- $('#fileupload').fileupload(
- 'option',
- 'redirect',
- window.location.href.replace(
- /\/[^\/]*$/,
- '/cors/result.html?%s'
- )
- );
- if (window.location.hostname === 'blueimp.github.io') {
- // Demo settings:
- $('#fileupload').fileupload('option', {
- url: '//jquery-file-upload.appspot.com/',
- // Enable image resizing, except for Android and Opera,
- // which actually support image resizing, but fail to
- // send Blob objects via XHR requests:
- disableImageResize: /Android(?!.*Chrome)|Opera/
- .test(window.navigator.userAgent),
- maxFileSize: 5000000,
- acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
- });
- // Upload server status check for browsers with CORS support:
- if ($.support.cors) {
- $.ajax({
- url: '//jquery-file-upload.appspot.com/',
- type: 'HEAD'
- }).fail(function () {
- $('<div class="alert alert-danger"/>')
- .text('Upload server currently unavailable - ' +
- new Date())
- .appendTo('#fileupload');
- });
- }
- } else {
- // Load existing files:
- $('#fileupload').addClass('fileupload-processing');
- $.ajax({
- // Uncomment the following to send cross-domain cookies:
- //xhrFields: {withCredentials: true},
- //url: $('#fileupload').fileupload('option', 'url'),
- url: '//localhost:8000/tracking/view/',
- dataType: 'json',
- context: $('#fileupload')[0]
- }).always(function () {
- $(this).removeClass('fileupload-processing');
- }).done(function (result) {
- $(this).fileupload('option', 'done')
- .call(this, null, {result: result});
- });
- }
- });
- //models.py
- class UploadFile(models.Model):
- files = models.FileField(upload_to="multiupload")
- slug = models.SlugField(max_length=50, blank=True)
- def __unicode__(self):
- return self.file.name
- @models.permalink
- def get_absolute_url(self):
- return ('upload-new', )
- def save(self, *args, **kwargs):
- self.slug = self.file.name
- super(UploadFile, self).save(*args, **kwargs)
- def delete(self, *args, **kwargs):
- """delete -- Remove to leave file."""
- self.file.delete(False)
- super(UploadFile, self).delete(*args, **kwargs)
- //views.py
- class UploadFileCreateView(CreateView):
- model = UploadFile
- def form_valid(self, form):
- self.object = form.save()
- files = [serialize(self.object)]
- data = {'files': files}
- response = JSONResponse(data, mimetype=response_mimetype(self.request))
- response['Content-Disposition'] = 'inline; filename=files.json'
- return response
- class BasicPlusVersionCreateView(UploadFileCreateView):
- template_name_suffix = '_basicplus_form'
- class jQueryVersionCreateView(UploadFileCreateView):
- template_name_suffix = '_jquery_form'
- class UploadFileDeleteView(DeleteView):
- model = UploadFile
- def delete(self, request, *args, **kwargs):
- self.object = self.get_object()
- self.object.delete()
- response = JSONResponse(True, mimetype=response_mimetype(request))
- response['Content-Disposition'] = 'inline; filename=files.json'
- return response
- class UploadFileListView(ListView):
- model = UploadFile
- def render_to_response(self, context, **response_kwargs):
- files = [ serialize(p) for p in self.get_queryset() ]
- data = {'files': files}
- response = JSONResponse(data, mimetype=response_mimetype(self.request))
- response['Content-Disposition'] = 'inline; filename=files.json'
- return response
- //response.py
- # encoding: utf-8
- from django.http import HttpResponse
- from django.utils import simplejson
- MIMEANY = '*/*'
- MIMEJSON = 'application/json'
- MIMETEXT = 'text/plain'
- def response_mimetype(request):
- """response_mimetype -- Return a proper response mimetype, accordingly to
- what the client accepts, as available in the `HTTP_ACCEPT` header.
- request -- a HttpRequest instance.
- """
- can_json = MIMEJSON in request.META['HTTP_ACCEPT']
- can_json |= MIMEANY in request.META['HTTP_ACCEPT']
- return MIMEJSON if can_json else MIMETEXT
- class JSONResponse(HttpResponse):
- """JSONResponse -- Extends HTTPResponse to handle JSON format response.
- This response can be used in any view that should return a json stream of
- data.
- Usage:
- def a_iew(request):
- content = {'key': 'value'}
- return JSONResponse(content, mimetype=response_mimetype(request))
- """
- def __init__(self, obj='', json_opts=None, mimetype=MIMEJSON, *args, **kwargs):
- json_opts = json_opts if isinstance(json_opts, dict) else {}
- content = simplejson.dumps(obj, **json_opts)
- super(JSONResponse, self).__init__(content, mimetype, *args, **kwargs)
- //serialize.py
- # encoding: utf-8
- import mimetypes
- import re
- from django.core.urlresolvers import reverse
- def order_name(name):
- """order_name -- Limit a text to 20 chars length, if necessary strips the
- middle of the text and substitute it for an ellipsis.
- name -- text to be limited.
- """
- name = re.sub(r'^.*/', '', name)
- if len(name) <= 20:
- return name
- return name[:10] + "..." + name[-7:]
- def serialize(instance, file_attr='file'):
- """serialize -- Serialize a Picture instance into a dict.
- instance -- Picture instance
- file_attr -- attribute name that contains the FileField or ImageField
- """
- obj = getattr(instance, file_attr)
- return {
- 'url': obj.url,
- 'name': order_name(obj.name),
- 'type': mimetypes.guess_type(obj.path)[0] or 'image/png',
- 'thumbnailUrl': obj.url,
- 'size': obj.size,
- 'deleteUrl': reverse('upload-delete', args=[instance.pk]),
- 'deleteType': 'DELETE',
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement