This commit is contained in:
SDE
2023-05-16 17:14:16 +03:00
commit c17da7eaab
157 changed files with 14503 additions and 0 deletions

1
files_widget/__init__.py Normal file
View File

@@ -0,0 +1 @@
from .fields import FileField, FilesField, ImageField, ImagesField

21
files_widget/admin.py Normal file
View File

@@ -0,0 +1,21 @@
from django.contrib import admin
from .models import IconSet, FileIcon
from .conf import *
# currently not used
class MyModelAdmin(admin.ModelAdmin):
def get_urls(self):
urls = super(MyModelAdmin, self).get_urls()
my_urls = patterns('',
(r'^my_view/$', self.my_view)
)
return my_urls + urls
def my_view(self, request):
# custom view which should return an HttpResponse
pass
#admin.site.register(IconSet)
#admin.site.register(FileIcon)

28
files_widget/conf.py Normal file
View File

@@ -0,0 +1,28 @@
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
MEDIA_URL = getattr(settings, 'MEDIA_URL')
MEDIA_ROOT = getattr(settings, 'MEDIA_ROOT')
TEMP_DIR = getattr(settings, 'FILES_WIDGET_TEMP_DIR', 'temp/uploads/')
TEMP_DIR_FORMAT = getattr(settings, 'FILES_WIDGET_TEMP_DIR_FORMAT', '%4d-%02d-%02d-%02d-%02d')
FILES_DIR = getattr(settings, 'FILES_WIDGET_FILES_DIR', 'uploads/from_admin/')
OLD_VALUE_STR = getattr(settings, 'FILES_WIDGET_OLD_VALUE_STR', 'old_%s_value')
DELETED_VALUE_STR = getattr(settings, 'FILES_WIDGET_DELETED_VALUE_STR', 'deleted_%s_value')
MOVED_VALUE_STR = getattr(settings, 'FILES_WIDGET_MOVED_VALUE_STR', 'moved_%s_value')
JQUERY_PATH = getattr(settings, 'FILES_WIDGET_JQUERY_PATH', '//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js')
JQUERY_UI_PATH = getattr(settings, 'FILES_WIDGET_JQUERY_UI_PATH', '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js')
USE_FILEBROWSER = getattr(settings, 'FILES_WIDGET_USE_FILEBROWSER', False)
FILEBROWSER_JS_PATH = getattr(settings, 'FILES_WIDGET_FILEBROWSER_JS_PATH', 'filebrowser/js/AddFileBrowser.js')
ADD_IMAGE_BY_URL = getattr(settings, 'FILES_WIDGET_ADD_IMAGE_BY_URL', True)
MAX_FILESIZE = getattr(settings, 'FILES_WIDGET_MAX_FILESIZE', 0)
FILE_TYPES = getattr(settings, 'FILES_WIDGET_FILE_TYPES', None)
USE_TRASH = getattr(settings, 'FILES_WIDGET_USE_TRASH', False)
TRASH_DIR = getattr(settings, 'FILES_WIDGET_TRASH_DIR', 'uploads/trash/files_widget/')
if not len(MEDIA_URL) or not len(MEDIA_ROOT) or not len(TEMP_DIR) or not len(FILES_DIR):
raise ImproperlyConfigured('MEDIA_URL, MEDIA_ROOT, FILES_WIDGET_TEMP_DIR and FILES_WIDGET_FILES_DIR must not be empty')
if TEMP_DIR == FILES_DIR:
raise ImproperlyConfigured('FILES_WIDGET_TEMP_DIR and FILES_WIDGET_FILES_DIR must be different')
if not MEDIA_ROOT.endswith('/'):
MEDIA_ROOT += '/'

292
files_widget/controllers.py Normal file
View File

@@ -0,0 +1,292 @@
import re
from six.moves import urllib
import os, os.path
from datetime import datetime
from django.conf import settings
import six
from django.utils.safestring import mark_safe
from .utils import curry
from django.core.files.images import ImageFile
from django.core.files.storage import get_storage_class
from django.contrib.staticfiles import finders
from sorl.thumbnail import get_thumbnail
from .conf import *
class FilePath(six.text_type):
def __new__(cls, str, instance=None, field=None, settings={}):
self = super(FilePath, cls).__new__(cls, str.strip())
self._instance = instance
self._field = field
self._exists = None
self._size = None
self._accessed_time = None
self._created_time = None
self._modified_time = None
self._thumbnails = {}
self.settings = {
'img_attrs': {},
'thumbnail_size': None,
'thumbnail_attrs': {},
}
self.settings.update(settings)
return self
def _html_attrs(self, **kwargs):
attrs = {}
attrs.update(kwargs)
if 'css_class' in attrs:
attrs['class'] = attrs['css_class']
del attrs['css_class']
return attrs
@property
def unescaped(self):
return urllib.parse.unquote(self)
@property
def escaped(self):
return urllib.parse.quote(self.unescaped)
@property
def url(self):
if not self.startswith('/') and self.find('//') == -1:
return os.path.join(MEDIA_URL, self.escaped)
return self.escaped
@property
def local_path(self):
if not self.startswith('/') and self.find('//') == -1:
return os.path.join(MEDIA_ROOT, urllib.parse.unquote(self))
return self
def _get_local_path_or_file(self):
# if file is in static instead of media directory, sorl raises
# a suspicious operation error. So we open it safely without errors.
if self.startswith('/'):
if self.startswith('/static/'):
path = self.replace('/static/', '')
elif self.startswith(settings.STATIC_URL):
path = self.replace(settings.STATIC_URL, '')
else:
return self.local_path
else:
return self.local_path
path = finders.find(urllib.parse.unquote(path))
image = ImageFile(open(path, 'r'))
return image
@property
def filename(self):
return urllib.parse.unquote(re.sub(r'^.+\/', '', self))
@property
def display_name(self):
without_extension = re.sub(r'\.[\w\d]+$', '', self.filename)
with_spaces = re.sub(r'_', ' ', without_extension)
return with_spaces
@property
def ext(self):
return re.sub(r'^.+\.', '', self.filename)
def exists(self):
if self._exists == None:
self._exists = os.path.exists(self.local_path)
return self._exists
def get_size(self):
if self._size == None:
self._size = os.path.getsize(self.local_path)
return self._size
def get_accessed_time(self):
if self._accessed_time == None:
self._accessed_time = datetime.fromtimestamp(os.path.getatime(self.local_path))
return self._accessed_time
def get_created_time(self):
if self._created_time == None:
self._created_time = datetime.fromtimestamp(os.path.getctime(self.local_path))
return self._created_time
def get_modified_time(self):
if self._modified_time == None:
self._modified_time = datetime.fromtimestamp(os.path.getmtime(self.local_path))
return self._modified_time
class ImagePath(FilePath):
def img_tag(self, **kwargs):
attrs = {}
attrs.update(self.settings['img_attrs'])
attrs.update(kwargs)
attrs = self._html_attrs(**attrs)
attrs_str = ''.join([
u'%s="%s" ' % (key, value)
for key, value in attrs.items()
])
return mark_safe(u'<img src="%s" %s/>' % (self.url, attrs_str))
def _thumbnail_file_format(self):
if self.ext.lower() in ['gif', 'png']:
return 'PNG'
return 'JPEG'
def thumbnail(self, size=None, **kwargs):
size = size or self.settings['thumbnail_size']
if not size:
raise Exception('No thumbnail size supplied')
attrs = {
'format': self._thumbnail_file_format(),
'upscale': False,
}
attrs.update(self.settings['thumbnail_attrs'])
attrs.update(kwargs)
all_attrs = { 'size': size }
all_attrs.update(attrs)
key = hash(frozenset(all_attrs))
if not key in self._thumbnails:
#self._thumbnails[key] = get_thumbnail(self._get_local_path_or_file(), size, **attrs)
self._thumbnails[key] = get_thumbnail(self.local_path, size, **attrs)
return self._thumbnails[key]
def thumbnail_tag(self, size, opts={}, **kwargs):
try:
thumbnail = self.thumbnail(size, **opts)
except EnvironmentError as e:
if settings.THUMBNAIL_DEBUG:
raise e
return ''
src = ImagePath(thumbnail.url, self._instance, self._field)
attrs = { 'width': thumbnail.width, 'height': thumbnail.height }
attrs.update(self.settings['img_attrs'])
attrs.update(kwargs)
return src.img_tag(**attrs)
def __getattr__(self, attr):
thumbnail_mxn = re.match(r'^thumbnail_(tag_)?(\d*x?\d+)$', attr)
if thumbnail_mxn:
tag = thumbnail_mxn.group(1) == 'tag_'
size = thumbnail_mxn.group(2)
if tag:
return curry(self.thumbnail_tag, size)
else:
return curry(self.thumbnail, size)
raise AttributeError
class FilePaths(six.text_type):
item_class = FilePath
def __new__(cls, str, instance=None, field=None, settings={}):
self = super(FilePaths, cls).__new__(cls, str)
self._instance = instance
self._field = field
self._all = None
self._length = None
self._current = 0
self.settings = {
'img_attrs': {},
'thumbnail_size': None,
'thumbnail_attrs': {},
}
self.settings.update(settings)
return self
def all(self):
if self._all == None:
self._all = []
for f in self.splitlines():
self._all.append(self._field.attr_class.item_class(f, self._instance, self._field, self.settings))
self._length = len(self._all)
return self._all
def count(self):
self.all()
return self._length
def first(self):
return self.all() and self.all()[0] or None
def last(self):
return self.all() and self.all()[-1] or None
def next(self):
f = self.all()[self._current]
self._current += 1
return f
def next_n(self, n):
files = self.all()[self._current:self._current+n]
self._current += n
return files
def next_all(self):
files = self.all()[self._current:]
self._current = self._length - 1
return files
def has_next(self):
self.all()
return max(0, self._length - self._current - 1)
def reset(self):
self._current = 0
def __getattr__(self, attr):
next_n = re.match(r'^next_(\d+)$', attr)
if next_n:
n = int(next_n.group(1))
return curry(self.next_n, n)
raise AttributeError
class ImagePaths(FilePaths):
item_class = ImagePath
def as_gallery(self):
raise NotImplementedError
def as_carousel(self):
raise NotImplementedError
class FilesDescriptor(object):
"""
Used django.db.models.fields.files.FileDescriptor as an example.
This descriptor returns an unicode object, with special methods
for formatting like filename(), absolute(), relative() and img_tag().
"""
def __init__(self, field):
self.field = field
def __get__(self, instance=None, owner=None):
if instance is None:
return self
files = instance.__dict__[self.field.name]
if isinstance(files, six.string_types) and not isinstance(files, (FilePath, FilePaths)):
attr = self.field.attr_class(files, instance, self.field)
instance.__dict__[self.field.name] = attr
return instance.__dict__[self.field.name]
def __set__(self, instance, value):
instance.__dict__[self.field.name] = value

104
files_widget/fields.py Normal file
View File

@@ -0,0 +1,104 @@
import os
from django.db import models
from django import forms
from django.core import exceptions, validators
from django.utils.translation import ugettext_lazy as _
from django.db.models.signals import post_save
from django.dispatch import receiver
from .forms import FilesFormField, BaseFilesWidget, FileWidget, FilesWidget, ImageWidget, ImagesWidget
from .files import manage_files_on_disk
from . import controllers
from .conf import *
def formfield_defaults(self, default_widget=None, widget=None, form_class=FilesFormField, required=True, **kwargs):
if not isinstance(widget, BaseFilesWidget):
widget = default_widget
defaults = {
'form_class': FilesFormField,
'fields': (forms.CharField(required=required), forms.CharField(required=False), forms.CharField(required=False), ),
'widget': widget,
}
defaults.update(kwargs)
return defaults
def save_all_data(self, instance, data):
# Save old data to know which images are deleted.
# We don't know yet if the form will really be saved.
old_data = getattr(instance, self.name)
setattr(instance, OLD_VALUE_STR % self.name, old_data)
setattr(instance, DELETED_VALUE_STR % self.name, data.deleted_files)
setattr(instance, MOVED_VALUE_STR % self.name, data.moved_files)
class FileField(models.CharField):
description = _("File")
attr_class = controllers.FilePath
def __init__(self, *args, **kwargs):
if 'max_length' not in kwargs:
kwargs['max_length'] = 200
super(FileField, self).__init__(*args, **kwargs)
def contribute_to_class(self, cls, name):
super(FileField, self).contribute_to_class(cls, name)
receiver(post_save, sender=cls)(manage_files_on_disk)
setattr(cls, self.name, controllers.FilesDescriptor(self))
def save_form_data(self, instance, data):
save_all_data(self, instance, data)
super(FileField, self).save_form_data(instance, data)
def formfield(self, default_widget=FileWidget(), **kwargs):
defaults = formfield_defaults(self, default_widget, **kwargs)
return super(FileField, self).formfield(**defaults)
class FilesField(models.TextField):
description = _("Files")
attr_class = controllers.FilePaths
def contribute_to_class(self, cls, name):
super(FilesField, self).contribute_to_class(cls, name)
receiver(post_save, sender=cls)(manage_files_on_disk)
setattr(cls, self.name, controllers.FilesDescriptor(self))
def save_form_data(self, instance, data):
save_all_data(self, instance, data)
super(FilesField, self).save_form_data(instance, data)
def formfield(self, default_widget=FilesWidget(), **kwargs):
defaults = formfield_defaults(self, default_widget, **kwargs)
return super(FilesField, self).formfield(**defaults)
class ImageField(FileField):
description = _("Image")
attr_class = controllers.ImagePath
def formfield(self, default_widget=ImageWidget(), **kwargs):
defaults = formfield_defaults(self, default_widget, **kwargs)
return super(ImageField, self).formfield(**defaults)
class ImagesField(FilesField):
description = _("Images")
attr_class = controllers.ImagePaths
def formfield(self, default_widget=ImagesWidget(), **kwargs):
defaults = formfield_defaults(self, default_widget, **kwargs)
return super(ImagesField, self).formfield(**defaults)
try:
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^topnotchdev\.files_widget\.fields\.FileField"])
add_introspection_rules([], ["^topnotchdev\.files_widget\.fields\.FilesField"])
add_introspection_rules([], ["^topnotchdev\.files_widget\.fields\.ImageField"])
add_introspection_rules([], ["^topnotchdev\.files_widget\.fields\.ImagesField"])
except ImportError:
pass

209
files_widget/files.py Normal file
View File

@@ -0,0 +1,209 @@
import os, os.path
from io import FileIO, BufferedWriter
import re
import time
from django.conf import settings
from django.core.files.storage import default_storage
from django.utils.translation import ugettext_lazy as _
from django.template.defaultfilters import slugify
from .conf import *
def is_file_image(path):
try:
from PIL import Image
im = Image.open(path)
im.verify()
return True
except Exception as e:
return False
def filename_from_path(path):
return re.sub(r'^.+/', '', path)
def model_slug(model):
return slugify(model._meta.verbose_name_plural)
def construct_temp_path(user):
now = time.localtime()[0:5]
dir_name = TEMP_DIR_FORMAT % now
return os.path.join(TEMP_DIR, dir_name, str(user.pk))
def construct_permanent_path(instance):
model_dir = model_slug(type(instance))
return os.path.join(FILES_DIR, model_dir, str(instance.pk))
def in_directory(path, directory):
# don't try to manipulate with ../../
full_path = os.path.join(MEDIA_ROOT, path)
return path.startswith(directory) and full_path == os.path.realpath(full_path)
def in_permanent_directory(path, instance):
full_path = os.path.join(MEDIA_ROOT, path)
return path.startswith(construct_permanent_path(instance)) and full_path == os.path.realpath(full_path)
def make_temp_directory(filename, user, short=False):
if not short:
public_dir = construct_temp_path(user)
else:
public_dir = f'{TEMP_DIR}'
full_dir = os.path.join(settings.MEDIA_ROOT, public_dir)
try:
if not os.path.exists(full_dir):
os.makedirs(full_dir)
except EnvironmentError:
# deepest dir already exists
pass
full_path = os.path.join(full_dir, filename)
available_full_path = default_storage.get_available_name(full_path)
return available_full_path
def make_permanent_directory(temp_path, instance):
public_dir = construct_permanent_path(instance)
filename = filename_from_path(temp_path)
full_dir = os.path.join(MEDIA_ROOT, public_dir)
if not os.path.exists(full_dir):
os.makedirs(full_dir)
full_path = os.path.join(full_dir, filename)
available_full_path = default_storage.get_available_name(full_path)
return available_full_path
def save_upload(uploaded, filename, raw_data, user):
'''
raw_data: if True, uploaded is an HttpRequest object with the file being
the raw post data
if False, uploaded has been submitted via the basic form
submission and is a regular Django UploadedFile in request.FILES
'''
path = make_temp_directory(filename, user, short=True)
public_path = path.replace(MEDIA_ROOT, '', 1)
#try:
with BufferedWriter(FileIO(path, "wb")) as dest:
# if the "advanced" upload, read directly from the HTTP request
# with the Django 1.3 functionality
if raw_data:
foo = uploaded.read(1024)
while foo:
dest.write(foo)
foo = uploaded.read(1024)
# if not raw, it was a form upload so read in the normal Django chunks fashion
else:
for c in uploaded.chunks():
dest.write(c)
# got through saving the upload, report success
return public_path
#except IOError:
# could not open the file most likely
# pass
return False
def try_to_recover_path(temp_path, instance):
filename = filename_from_path(temp_path)
permanent_directory = construct_permanent_path(instance)
permanent_path = os.path.join(permanent_directory, filename)
full_path = os.path.join(MEDIA_ROOT, permanent_path)
if os.path.exists(full_path):
return permanent_path, True
else:
return temp_path, False
def move_to_permanent_directory(temp_path, instance):
if temp_path.startswith('/') or temp_path.find('//') != -1 \
or in_permanent_directory(temp_path, instance):
return temp_path, False
full_path = make_permanent_directory(temp_path, instance)
public_path = full_path.replace(MEDIA_ROOT, '', 1)
full_temp_path = os.path.join(MEDIA_ROOT, temp_path)
try:
os.link(full_temp_path, full_path)
except EnvironmentError:
return try_to_recover_path(temp_path, instance)
if in_directory(temp_path, TEMP_DIR):
try:
os.remove(full_temp_path)
except EnvironmentError:
return try_to_recover_path(temp_path, instance)
return public_path, True
def manage_files_on_disk(sender, instance, **kwargs):
# Receiver of Django post_save signal.
# At this point we know that the model instance has been saved into the db.
from .fields import ImagesField, ImageField, FilesField, FileField
fields = [field for field in sender._meta.fields if type(field) in [ImagesField, ImageField, FilesField, FileField]]
for field in fields:
old_value_attr = OLD_VALUE_STR % field.name
deleted_value_attr = DELETED_VALUE_STR % field.name
moved_value_attr = MOVED_VALUE_STR % field.name
if not hasattr(instance, old_value_attr):
continue
old_images = (getattr(instance, old_value_attr) or '').splitlines()
current_images = (getattr(instance, field.name) or '').splitlines()
deleted_images = (getattr(instance, deleted_value_attr) or '').splitlines()
moved_images = (getattr(instance, moved_value_attr) or '').splitlines()
new_images = []
changed = False
# Delete removed images from disk if they are in our FILES_DIR.
# we implement redundant checks to be absolutely sure that
# files must be deleted. For example, if a JS error leads to
# incorrect file lists in the hidden inputs, we reconstruct the old value.
#
# O = old_images, C = current_images, D = deleted_images
#
# what do we do with files that appear in:
#
# --- (OK) do nothing, we don't even know it's name :)
# --D (OK) if in temp dir or permanent dir of inst: delete from disk
# -C- (OK) if not in permanent dir of inst, create hard link if possible;
# if in temp dir, delete
# -CD (ERROR) show warning message after save
# O-- (ERROR) put back in current, show warning message after save
# O-D (OK) if in temp dir or permanent dir of inst: delete from disk
# OC- (OK) if not in permanent dir of inst, create hard link if possible;
# if in temp dir, delete
# OCD (ERROR) show warning message after save
for img in current_images:
# OC-, -C-, OCD & -CD
new_path = img
if in_directory(img, TEMP_DIR) or in_directory(img, FILES_DIR):
new_path, path_changed = move_to_permanent_directory(img, instance)
if path_changed:
changed = True
new_images.append(new_path)
for img in deleted_images:
if img not in current_images:
# --D & O-D
if in_permanent_directory(img, instance) or in_directory(img, TEMP_DIR):
try:
os.remove(os.path.join(MEDIA_ROOT, img))
except EnvironmentError as e:
pass
for img in old_images:
if img not in current_images and img not in deleted_images and img not in moved_images:
# O--
changed = True
new_images.append(img)
delattr(instance, old_value_attr)
delattr(instance, deleted_value_attr)
delattr(instance, moved_value_attr)
if changed:
setattr(instance, field.name, '\n'.join(new_images))
instance.save()

View File

@@ -0,0 +1,2 @@
from .fields import *
from .widgets import *

View File

@@ -0,0 +1,62 @@
from django import forms
from django.core import exceptions, validators
from django.utils.translation import ugettext_lazy as _
import six
from files_widget.conf import *
class UnicodeWithAttr(six.text_type):
deleted_files = None
moved_files = None
class FilesFormField(forms.MultiValueField):
def __init__(self, max_length=None, **kwargs):
super(FilesFormField, self).__init__(**kwargs)
def compress(self, data_list):
files = UnicodeWithAttr(data_list[0])
files.deleted_files = data_list[1]
files.moved_files = data_list[2]
return files
def clean(self, value):
"""
This is a copy of MultiValueField.clean() with a BUGFIX:
- if self.required and field_value in validators.EMPTY_VALUES:
+ if field.required and field_value in validators.EMPTY_VALUES:
"""
from django.forms.utils import ErrorList
from django.core.exceptions import ValidationError
clean_data = []
errors = ErrorList()
if not value or isinstance(value, (list, tuple)):
if not value or not [v for v in value if v not in validators.EMPTY_VALUES]:
if self.required:
raise ValidationError(self.error_messages['required'])
else:
return self.compress(value)
else:
raise ValidationError(self.error_messages['invalid'])
for i, field in enumerate(self.fields):
try:
field_value = value[i]
except IndexError:
field_value = None
if field.required and field_value in validators.EMPTY_VALUES:
raise ValidationError(self.error_messages['required'])
try:
clean_data.append(field.clean(field_value))
except ValidationError as e:
# Collect all validation errors in a single list, which we'll
# raise at the end of clean(), rather than raising a single
# exception for the first error we encounter.
errors.extend(e.messages)
if errors:
raise ValidationError(errors)
out = self.compress(clean_data)
self.validate(out)
self.run_validators(out)
return out

View File

@@ -0,0 +1,100 @@
from django import forms
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from files_widget.conf import *
def use_filebrowser():
if USE_FILEBROWSER:
try:
import filebrowser
return True
except:
try:
import filebrowser_safe
return True
except:
pass
pass
return False
TO_HIDE_ATTRS = {'class': 'hidden'}
class BaseFilesWidget(forms.MultiWidget):
def __init__(self,
multiple=False,
preview_size=150,
template="files_widget/files_widget.html",
widgets=(forms.HiddenInput,
forms.HiddenInput,
forms.HiddenInput),
**kwargs):
super(BaseFilesWidget, self).__init__(widgets, **kwargs)
self.multiple = multiple
self.preview_size = preview_size
self.template = template
class Media:
js = [
JQUERY_PATH,
JQUERY_UI_PATH,
'files_widget/js/jquery.iframe-transport.js',
'files_widget/js/jquery.fileupload.js',
'files_widget/js/widgets.js',
]
if use_filebrowser():
js.append(FILEBROWSER_JS_PATH)
css = {
'all': (
'files_widget/css/widgets.css',
),
}
@property
def is_hidden(self):
return False
def decompress(self, value):
if value:
return [value, '', '', ]
return ['', '', '', ]
def render(self, name, value, attrs=None, renderer=None):
if not isinstance(value, list):
value = self.decompress(value)
files, deleted_files, moved_files = value
context = {
'MEDIA_URL': settings.MEDIA_URL,
'STATIC_URL': settings.STATIC_URL,
'use_filebrowser': use_filebrowser(),
'add_image_by_url': ADD_IMAGE_BY_URL,
'input_string': super(BaseFilesWidget, self).render(name, value, attrs, renderer),
'name': name,
'files': files,
'deleted_files': deleted_files,
'multiple': self.multiple and 1 or 0,
'preview_size': str(self.preview_size),
}
return renderer.render(self.template, context)
class FileWidget(BaseFilesWidget):
def __init__(self, multiple=False, preview_size=128, **kwargs):
super(FileWidget, self).__init__(multiple, preview_size, template="files_widget/files_widget.html", **kwargs)
class FilesWidget(BaseFilesWidget):
def __init__(self, multiple=True, preview_size=64, **kwargs):
super(FilesWidget, self).__init__(multiple, preview_size, template="files_widget/files_widget.html", **kwargs)
class ImageWidget(BaseFilesWidget):
def __init__(self, multiple=False, preview_size=250, **kwargs):
super(ImageWidget, self).__init__(multiple, preview_size, template="files_widget/images_widget.html", **kwargs)
class ImagesWidget(BaseFilesWidget):
def __init__(self, multiple=True, preview_size=150, **kwargs):
super(ImagesWidget, self).__init__(multiple, preview_size, template="files_widget/images_widget.html", **kwargs)

View File

@@ -0,0 +1,64 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2018-10-10 08:53+0800\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=1; plural=0;\n"
#: files_widget/fields.py:39
msgid "File"
msgstr ""
#: files_widget/fields.py:60
msgid "Files"
msgstr ""
#: files_widget/fields.py:78
msgid "Image"
msgstr ""
#: files_widget/fields.py:87
msgid "Images"
msgstr ""
#: files_widget/templates/files_widget/files_widget.html:3
msgid "undo"
msgstr ""
#: files_widget/templates/files_widget/files_widget.html:6
msgid "Drop multiple images here to upload"
msgstr ""
#: files_widget/templates/files_widget/files_widget.html:8
msgid "Drop an image here to upload"
msgstr ""
#: files_widget/templates/files_widget/files_widget.html:32
msgid "Upload"
msgstr ""
#: files_widget/templates/files_widget/files_widget.html:37
msgid "Library"
msgstr ""
#: files_widget/templates/files_widget/files_widget.html:41
#: files_widget/templates/files_widget/files_widget.html:43
msgid "Add by url..."
msgstr ""
#: files_widget/templates/files_widget/files_widget.html:60
msgid "Images to be removed"
msgstr ""

View File

@@ -0,0 +1,65 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2018-10-10 08:51+0800\n"
"PO-Revision-Date: 2018-10-10 08:58+0806\n"
"Last-Translator: b' <admin@xx.com>'\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=1; plural=0;\n"
"X-Translated-Using: django-rosetta 0.9.0\n"
#: files_widget/fields.py:39
msgid "File"
msgstr "文件"
#: files_widget/fields.py:60
msgid "Files"
msgstr "文件"
#: files_widget/fields.py:78
msgid "Image"
msgstr "图片"
#: files_widget/fields.py:87
msgid "Images"
msgstr "图片"
#: files_widget/templates/files_widget/files_widget.html:3
msgid "undo"
msgstr "撤销"
#: files_widget/templates/files_widget/files_widget.html:6
msgid "Drop multiple images here to upload"
msgstr "拖动多个图片文件来上传"
#: files_widget/templates/files_widget/files_widget.html:8
msgid "Drop an image here to upload"
msgstr "拖动一个图片文件来上传"
#: files_widget/templates/files_widget/files_widget.html:32
msgid "Upload"
msgstr "上传"
#: files_widget/templates/files_widget/files_widget.html:37
msgid "Library"
msgstr "库"
#: files_widget/templates/files_widget/files_widget.html:41
#: files_widget/templates/files_widget/files_widget.html:43
msgid "Add by url..."
msgstr "添加URL"
#: files_widget/templates/files_widget/files_widget.html:60
msgid "Images to be removed"
msgstr "待删除的图片"

View File

@@ -0,0 +1,54 @@
# Generated by Django 2.1.2 on 2018-10-09 23:37
from django.db import migrations, models
import django.db.models.deletion
import files_widget.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0009_alter_user_last_name_max_length'),
]
operations = [
migrations.CreateModel(
name='FileIcon',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('extension', models.CharField(blank=True, max_length=100, null=True)),
('image', files_widget.fields.ImageField(max_length=200)),
('display_text_overlay', models.BooleanField(default=True)),
('overlay_text', models.CharField(blank=True, help_text='Leave blank to display file extension', max_length=7, null=True)),
('base_color', models.CharField(blank=True, max_length=12, null=True)),
],
),
migrations.CreateModel(
name='IconSet',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50, unique=True)),
('css_path', models.CharField(blank=True, help_text='Optional css file for icon styling', max_length=200, null=True)),
('active', models.BooleanField(default=True)),
('priority', models.IntegerField(default=1)),
('default_icon', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='files_widget.FileIcon')),
],
),
migrations.CreateModel(
name='GlobalPermission',
fields=[
],
options={
'proxy': True,
'indexes': [],
},
bases=('auth.permission',),
),
migrations.AddField(
model_name='fileicon',
name='icon_set',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='files_widget.IconSet'),
),
]

View File

@@ -0,0 +1,19 @@
# Generated by Django 2.2.16 on 2022-11-11 18:37
from django.db import migrations
import files_widget.fields
class Migration(migrations.Migration):
dependencies = [
('files_widget', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='fileicon',
name='image',
field=files_widget.fields.ImageField(max_length=200),
),
]

View File

55
files_widget/models.py Normal file
View File

@@ -0,0 +1,55 @@
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Group, Permission
from .fields import ImageField
class GlobalPermissionManager(models.Manager):
def get_query_set(self):
return super(GlobalPermissionManager, self).\
get_query_set().filter(content_type__name='global_permission')
class GlobalPermission(Permission):
"""A global permission, not attached to a model"""
objects = GlobalPermissionManager()
class Meta:
proxy = True
def save(self, *args, **kwargs):
ct, created = ContentType.objects.get_or_create(
name="global_permission", app_label=self._meta.app_label
)
self.content_type = ct
super(GlobalPermission, self).save(*args, **kwargs)
try:
permission = GlobalPermission.objects.get_or_create(
codename='can_upload_files',
name='Can Upload Files',
)
except:
# "Table 'fileswidgettest16.auth_permission' doesn't exist"
# it should exist the next time that this file is loaded
pass
class IconSet(models.Model):
name = models.CharField(max_length=50, unique=True)
css_path = models.CharField(max_length=200, blank=True, null=True, help_text='Optional css file for icon styling')
active = models.BooleanField(default=True)
priority = models.IntegerField(default=1)
default_icon = models.ForeignKey('files_widget.FileIcon', null=True, blank=True, on_delete=models.SET_NULL)
class FileIcon(models.Model):
icon_set = models.ForeignKey('files_widget.IconSet', on_delete=models.CASCADE)
extension = models.CharField(max_length=100, blank=True, null=True)
image = ImageField()
display_text_overlay = models.BooleanField(default=True)
overlay_text = models.CharField(max_length=7, blank=True, null=True, help_text='Leave blank to display file extension')
base_color = models.CharField(max_length=12, blank=True, null=True)

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 185 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 223 KiB

View File

@@ -0,0 +1,294 @@
.files-widget {
display: inline-block;
width: 100%;
}
.files-widget-dropbox {
width: 100%;
min-height: 100px;
border: 1px solid transparent;
margin: 0 -3px;
display: inline-block;
}
.files-widget-dropbox.dragging-files {
background: rgba(0, 0, 0, .05);
border: 1px dashed rgba(0, 0, 0, .2);
}
.files-widget-dropbox.dragging-files.dragover {
background: rgba(0, 0, 0, .1);
border: 1px dashed rgba(0, 0, 0, .4);
}
.files-widget-dropbox .message {
display: block;
color: #a0a2a4;
margin: 30px;
text-align: center;
}
/*для файлов*/
.files-widget-dropbox .preview.filetype, .files-widget-dropbox .sortable-placeholder {
padding: 5px;
display: flex;
vertical-align: middle;
position: relative;
text-align: center;
width: 400px;
float: left;
margin-right: 10px;
}
/*для картинок*/
.files-widget-dropbox .preview, .files-widget-dropbox .sortable-placeholder {
padding: 5px;
display: inline-block;
vertical-align: middle;
position: relative;
text-align: center;
}
.files-widget-dropbox .sortable-placeholder {
background: rgba(0, 0, 0, .1);
}
.files-widget .image-holder {
display: inline-block;
position: relative;
border: 3px solid white;
box-shadow: 0 1px 4px rgba(0, 0, 0, .8);
border-radius: 3px;
background: white;
text-align: center;
}
.files-widget-dropbox .image-holder {
min-height: 50px;
/*min-width: 50px;*/
line-height: 50px;
}
.files-widget-dropbox .image-holder.icon100 {
min-height: 100px;
/*min-width: 100px;*/
line-height: 100px;
}
.files-widget-dropbox .image-holder.icon30 {
min-height: 30px;
/*min-width: 30px;*/
line-height: 30px;
margin-right: 10px;
}
.files-widget-dropbox .preview .thumbnail {
vertical-align: middle;
background: url(/static/files_widget/img/file-icons/file_icon.png) left top;
height: 50px;
/*width: 50px;*/
}
.files-widget-dropbox .preview .thumbnail.icon100 {
vertical-align: middle;
background: url(/static/files_widget/img/file-icons/file_icon.png) left top;
height: 100px;
/*width: 100px;*/
}
.files-widget-dropbox .preview .thumbnail.icon30 {
vertical-align: middle;
background: url(/static/files_widget/img/file-icons/file_icon.png) left top;
height: 30px;
/*width: 100px;*/
}
.file-name-for-icon100 {
overflow: hidden;
width: 100px;
text-overflow: ellipsis;
white-space: nowrap;
height: 10px;
margin-top: 5px;
font-size: 10px;
}
.file-name-for-icon30 {
overflow: hidden;
width: 100%;
/*text-overflow: ellipsis;*/
/*white-space: nowrap;*/
height: 100%;
margin-top: 5px;
font-size: 10px;
text-align: left;
}
.files-widget-dropbox .preview.new .thumbnail {
opacity: .5;
}
.files-widget-dropbox .buttons {
position: absolute;
top: -10px;
right: -10px;
opacity: 0;
white-space: nowrap;
display: block;
}
.files-widget-dropbox .buttons img {
vertical-align: top;
}
.files-widget-dropbox .preview:hover .buttons {
opacity: 1;
}
.files-widget-dropbox .preview.ui-sortable-helper .buttons,
.files-widget-dropbox .preview.new .buttons {
display: none;
}
.files-widget-dropbox .preview:hover .buttons a {
margin: -2px;
}
.files-widget-dropbox .uploaded {
position: absolute;
top:0;
left:0;
height:100%;
width:100%;
background: url('../img/done.png') no-repeat center center rgba(255,255,255,0.5);
display: none;
}
.files-widget-dropbox .preview.done .uploaded {
display: block;
}
.files-widget-dropbox .filename {
display: block;
position: absolute;
left: 0;
right: 0;
top: 20px;
overflow: hidden;
}
.files-widget-dropbox .progress-holder {
position: absolute;
background-color: #252f38;
height: 10px;
right: 8px;
left: 8px;
bottom: 8px;
box-shadow: 0 0 2px #000;
}
.files-widget-dropbox .progress {
background-color: #2586d0;
position: absolute;
height: 100%;
left: 0;
width: 0;
box-shadow: 0 0 1px rgba(255, 255, 255, 0.4) inset;
-moz-transition: 0.25s;
-webkit-transition: 0.25s;
-o-transition: 0.25s;
transition: 0.25s;
}
.files-widget-dropbox .preview.done .progress {
width:100% !important;
}
.files-widget .controls {
padding: 8px 0 0;
text-align: left;
}
.files-widget .controls .fake-files-input {
margin-left: 2px;
position: relative;
display: inline-block;
overflow: hidden;
}
.files-widget .controls .files-input {
padding: 4px;
opacity: .0001;
position: absolute;
top: 0;
bottom: 0;
right: 0;
cursor: pointer;
}
.files-widget .controls input[type=text].add-by-url {
width: 300px;
}
.files-widget .controls .upload-progress-stats {
float: right;
display: block;
padding-top: 5px;
color: #888;
}
.files-widget-deleted {
}
.files-widget-deleted p {
color: #bf3030;
border-bottom: 1px solid #e0e0e0;
padding: 0 1px !important;
margin-top: 10px;
margin-left: 0 !important;
}
.files-widget-deleted .deleted-list {
border-top: 1px solid white;
padding-top: 5px;
}
.files-widget-deleted .deleted-file {
height: 38px;
line-height: 38px;
margin-bottom: 5px;
}
.files-widget-deleted .deleted-file > span {
display: inline-block;
vertical-align: middle;
}
.files-widget-deleted .deleted-file .image-holder {
min-height: 32px;
min-width: 32px;
line-height: 32px;
margin: 0 5px 0 3px;
}
.files-widget-deleted .deleted-file .icon {
max-height: 32px;
max-width: 32px;
vertical-align: middle;
}
.files-widget-deleted .deleted-file .name {
white-space: nowrap;
text-decoration: line-through;
margin: 0 10px;
}
.files-widget-deleted .deleted-file .undo {
font-weight: bold;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 B

View File

@@ -0,0 +1,348 @@
/*
* jQuery File Upload AngularJS Plugin 1.0.1
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2013, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/*jslint nomen: true, unparam: true */
/*global angular */
(function () {
'use strict';
angular.module('blueimp.fileupload', [])
.provider('fileUpload', function () {
var scopeApply = function () {
var scope = angular.element(this)
.fileupload('option', 'scope')();
if (!scope.$$phase) {
scope.$apply();
}
},
$config;
$config = this.defaults = {
handleResponse: function (e, data) {
var files = data.result && data.result.files;
if (files) {
data.scope().replace(data.files, files);
} else if (data.errorThrown ||
data.textStatus === 'error') {
data.files[0].error = data.errorThrown ||
data.textStatus;
}
},
add: function (e, data) {
var scope = data.scope();
data.process(function () {
return scope.process(data);
}).always(
function () {
var file = data.files[0],
submit = function () {
return data.submit();
};
file.$cancel = function () {
scope.clear(data.files);
return data.abort();
};
file.$state = function () {
return data.state();
};
file.$progress = function () {
return data.progress();
};
file.$response = function () {
return data.response();
};
if (file.$state() === 'rejected') {
file._$submit = submit;
} else {
file.$submit = submit;
}
scope.$apply(function () {
var method = scope.option('prependFiles') ?
'unshift' : 'push';
Array.prototype[method].apply(
scope.queue,
data.files
);
if (file.$submit &&
(scope.option('autoUpload') ||
data.autoUpload) &&
data.autoUpload !== false) {
file.$submit();
}
});
}
);
},
progress: function (e, data) {
data.scope().$apply();
},
done: function (e, data) {
var that = this;
data.scope().$apply(function () {
data.handleResponse.call(that, e, data);
});
},
fail: function (e, data) {
var that = this;
if (data.errorThrown === 'abort') {
return;
}
if (data.dataType.indexOf('json') === data.dataType.length - 4) {
try {
data.result = angular.fromJson(data.jqXHR.responseText);
} catch (err) {}
}
data.scope().$apply(function () {
data.handleResponse.call(that, e, data);
});
},
stop: scopeApply,
processstart: scopeApply,
processstop: scopeApply,
getNumberOfFiles: function () {
return this.scope().queue.length;
},
dataType: 'json',
prependFiles: true,
autoUpload: false
};
this.$get = [
function () {
return {
defaults: $config
};
}
];
})
.provider('formatFileSizeFilter', function () {
var $config = this.defaults = {
// Byte units following the IEC format
// http://en.wikipedia.org/wiki/Kilobyte
units: [
{size: 1000000000, suffix: ' GB'},
{size: 1000000, suffix: ' MB'},
{size: 1000, suffix: ' KB'}
]
};
this.$get = function () {
return function (bytes) {
if (!angular.isNumber(bytes)) {
return '';
}
var unit = true,
i = -1;
while (unit) {
unit = $config.units[i += 1];
if (i === $config.units.length - 1 || bytes >= unit.size) {
return (bytes / unit.size).toFixed(2) + unit.suffix;
}
}
};
};
})
.controller('FileUploadController', [
'$scope', '$element', '$attrs', 'fileUpload',
function ($scope, $element, $attrs, fileUpload) {
$scope.disabled = angular.element('<input type="file">')
.prop('disabled');
$scope.queue = $scope.queue || [];
$scope.clear = function (files) {
var queue = this.queue,
i = queue.length,
file = files,
length = 1;
if (angular.isArray(files)) {
file = files[0];
length = files.length;
}
while (i) {
if (queue[i -= 1] === file) {
return queue.splice(i, length);
}
}
};
$scope.replace = function (oldFiles, newFiles) {
var queue = this.queue,
file = oldFiles[0],
i,
j;
for (i = 0; i < queue.length; i += 1) {
if (queue[i] === file) {
for (j = 0; j < newFiles.length; j += 1) {
queue[i + j] = newFiles[j];
}
return;
}
}
};
$scope.progress = function () {
return $element.fileupload('progress');
};
$scope.active = function () {
return $element.fileupload('active');
};
$scope.option = function (option, data) {
return $element.fileupload('option', option, data);
};
$scope.add = function (data) {
return $element.fileupload('add', data);
};
$scope.send = function (data) {
return $element.fileupload('send', data);
};
$scope.process = function (data) {
return $element.fileupload('process', data);
};
$scope.processing = function (data) {
return $element.fileupload('processing', data);
};
$scope.applyOnQueue = function (method) {
var list = this.queue.slice(0),
i,
file;
for (i = 0; i < list.length; i += 1) {
file = list[i];
if (file[method]) {
file[method]();
}
}
};
$scope.submit = function () {
this.applyOnQueue('$submit');
};
$scope.cancel = function () {
this.applyOnQueue('$cancel');
};
// The fileupload widget will initialize with
// the options provided via "data-"-parameters,
// as well as those given via options object:
$element.fileupload(angular.extend(
{scope: function () {
return $scope;
}},
fileUpload.defaults
)).on('fileuploadadd', function (e, data) {
data.scope = $scope.option('scope');
}).on([
'fileuploadadd',
'fileuploadsubmit',
'fileuploadsend',
'fileuploaddone',
'fileuploadfail',
'fileuploadalways',
'fileuploadprogress',
'fileuploadprogressall',
'fileuploadstart',
'fileuploadstop',
'fileuploadchange',
'fileuploadpaste',
'fileuploaddrop',
'fileuploaddragover',
'fileuploadchunksend',
'fileuploadchunkdone',
'fileuploadchunkfail',
'fileuploadchunkalways',
'fileuploadprocessstart',
'fileuploadprocess',
'fileuploadprocessdone',
'fileuploadprocessfail',
'fileuploadprocessalways',
'fileuploadprocessstop'
].join(' '), function (e, data) {
$scope.$emit(e.type, data);
});
// Observe option changes:
$scope.$watch(
$attrs.fileupload,
function (newOptions, oldOptions) {
if (newOptions) {
$element.fileupload('option', newOptions);
}
}
);
}
])
.controller('FileUploadProgressController', [
'$scope', '$attrs', '$parse',
function ($scope, $attrs, $parse) {
var fn = $parse($attrs.progress),
update = function () {
var progress = fn($scope);
if (!progress || !progress.total) {
return;
}
$scope.num = Math.floor(
progress.loaded / progress.total * 100
);
};
update();
$scope.$watch(
$attrs.progress + '.loaded',
function (newValue, oldValue) {
if (newValue !== oldValue) {
update();
}
}
);
}
])
.controller('FileUploadPreviewController', [
'$scope', '$element', '$attrs', '$parse',
function ($scope, $element, $attrs, $parse) {
var fn = $parse($attrs.preview),
file = fn($scope);
if (file.preview) {
$element.append(file.preview);
}
}
])
.directive('fileupload', function () {
return {
controller: 'FileUploadController'
};
})
.directive('progress', function () {
return {
controller: 'FileUploadProgressController'
};
})
.directive('preview', function () {
return {
controller: 'FileUploadPreviewController'
};
})
.directive('download', function () {
return function (scope, elm, attrs) {
elm.on('dragstart', function (e) {
try {
e.originalEvent.dataTransfer.setData(
'DownloadURL',
[
'application/octet-stream',
elm.prop('download'),
elm.prop('href')
].join(':')
);
} catch (err) {}
});
};
});
}());

View File

@@ -0,0 +1,158 @@
/*
* jQuery File Upload Processing Plugin 1.1
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2012, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/*jslint nomen: true, unparam: true */
/*global define, window */
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define([
'jquery',
'./jquery.fileupload'
], factory);
} else {
// Browser globals:
factory(
window.jQuery
);
}
}(function ($) {
'use strict';
var originalAdd = $.blueimp.fileupload.prototype.options.add;
// The File Upload Processing plugin extends the fileupload widget
// with file processing functionality:
$.widget('blueimp.fileupload', $.blueimp.fileupload, {
options: {
// The list of processing actions:
processQueue: [
/*
{
action: 'log',
type: 'debug'
}
*/
],
add: function (e, data) {
var $this = $(this);
data.process(function () {
return $this.fileupload('process', data);
});
originalAdd.call(this, e, data);
}
},
processActions: {
/*
log: function (data, options) {
console[options.type](
'Processing "' + data.files[data.index].name + '"'
);
}
*/
},
_processFile: function (data) {
var that = this,
dfd = $.Deferred().resolveWith(that, [data]),
chain = dfd.promise();
this._trigger('process', null, data);
$.each(data.processQueue, function (i, settings) {
var func = function (data) {
return that.processActions[settings.action].call(
that,
data,
settings
);
};
chain = chain.pipe(func, settings.always && func);
});
chain
.done(function () {
that._trigger('processdone', null, data);
that._trigger('processalways', null, data);
})
.fail(function () {
that._trigger('processfail', null, data);
that._trigger('processalways', null, data);
});
return chain;
},
// Replaces the settings of each processQueue item that
// are strings starting with an "@", using the remaining
// substring as key for the option map,
// e.g. "@autoUpload" is replaced with options.autoUpload:
_transformProcessQueue: function (options) {
var processQueue = [];
$.each(options.processQueue, function () {
var settings = {};
$.each(this, function (key, value) {
if ($.type(value) === 'string' &&
value.charAt(0) === '@') {
settings[key] = options[value.slice(1)];
} else {
settings[key] = value;
}
});
processQueue.push(settings);
});
options.processQueue = processQueue;
},
// Returns the number of files currently in the processsing queue:
processing: function () {
return this._processing;
},
// Processes the files given as files property of the data parameter,
// returns a Promise object that allows to bind callbacks:
process: function (data) {
var that = this,
options = $.extend({}, this.options, data);
if (options.processQueue && options.processQueue.length) {
this._transformProcessQueue(options);
if (this._processing === 0) {
this._trigger('processstart');
}
$.each(data.files, function (index, file) {
var opts = index ? $.extend({}, options) : options,
func = function () {
return that._processFile(opts);
};
opts.index = index;
that._processing += 1;
that._processingQueue = that._processingQueue.pipe(func, func)
.always(function () {
that._processing -= 1;
if (that._processing === 0) {
that._trigger('processstop');
}
});
});
}
return this._processingQueue;
},
_create: function () {
this._super();
this._processing = 0;
this._processingQueue = $.Deferred().resolveWith(this)
.promise();
}
});
}));

View File

@@ -0,0 +1,212 @@
/*
* jQuery File Upload Image Resize Plugin 1.1.2
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2013, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/*jslint nomen: true, unparam: true, regexp: true */
/*global define, window */
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define([
'jquery',
'load-image',
'canvas-to-blob',
'./jquery.fileupload-process'
], factory);
} else {
// Browser globals:
factory(
window.jQuery,
window.loadImage
);
}
}(function ($, loadImage) {
'use strict';
// Prepend to the default processQueue:
$.blueimp.fileupload.prototype.options.processQueue.unshift(
{
action: 'loadImage',
fileTypes: '@loadImageFileTypes',
maxFileSize: '@loadImageMaxFileSize',
noRevoke: '@loadImageNoRevoke',
disabled: '@disableImageLoad'
},
{
action: 'resizeImage',
maxWidth: '@imageMaxWidth',
maxHeight: '@imageMaxHeight',
minWidth: '@imageMinWidth',
minHeight: '@imageMinHeight',
crop: '@imageCrop',
disabled: '@disableImageResize'
},
{
action: 'saveImage',
disabled: '@disableImageResize'
},
{
action: 'resizeImage',
maxWidth: '@previewMaxWidth',
maxHeight: '@previewMaxHeight',
minWidth: '@previewMinWidth',
minHeight: '@previewMinHeight',
crop: '@previewCrop',
canvas: '@previewAsCanvas',
disabled: '@disableImagePreview'
},
{
action: 'setImage',
// The name of the property the resized image
// is saved as on the associated file object:
name: 'preview',
disabled: '@disableImagePreview'
}
);
// The File Upload Resize plugin extends the fileupload widget
// with image resize functionality:
$.widget('blueimp.fileupload', $.blueimp.fileupload, {
options: {
// The regular expression for the types of images to load:
// matched against the file type:
loadImageFileTypes: /^image\/(gif|jpeg|png)$/,
// The maximum file size of images to load:
loadImageMaxFileSize: 5000000, // 5MB
// The maximum width of resized images:
imageMaxWidth: 1920,
// The maximum height of resized images:
imageMaxHeight: 1080,
// Define if resized images should be cropped or only scaled:
imageCrop: false,
// Disable the resize image functionality by default:
disableImageResize: true,
// The maximum width of the preview images:
previewMaxWidth: 80,
// The maximum height of the preview images:
previewMaxHeight: 80,
// Define if preview images should be cropped or only scaled:
previewCrop: false,
// Define if preview images should be resized as canvas elements:
previewAsCanvas: true
},
processActions: {
// Loads the image given via data.files and data.index
// as img element if the browser supports canvas.
// Accepts the options fileTypes (regular expression)
// and maxFileSize (integer) to limit the files to load:
loadImage: function (data, options) {
if (options.disabled) {
return data;
}
var that = this,
file = data.files[data.index],
dfd = $.Deferred();
if (($.type(options.maxFileSize) === 'number' &&
file.size > options.maxFileSize) ||
(options.fileTypes &&
!options.fileTypes.test(file.type)) ||
!loadImage(
file,
function (img) {
if (!img.src) {
return dfd.rejectWith(that, [data]);
}
data.img = img;
dfd.resolveWith(that, [data]);
},
options
)) {
dfd.rejectWith(that, [data]);
}
return dfd.promise();
},
// Resizes the image given as data.canvas or data.img
// and updates data.canvas or data.img with the resized image.
// Accepts the options maxWidth, maxHeight, minWidth,
// minHeight, canvas and crop:
resizeImage: function (data, options) {
options = $.extend({canvas: true}, options);
var img = (options.canvas && data.canvas) || data.img,
canvas;
if (img && !options.disabled) {
canvas = loadImage.scale(img, options);
if (canvas && (canvas.width !== img.width ||
canvas.height !== img.height)) {
data[canvas.getContext ? 'canvas' : 'img'] = canvas;
}
}
return data;
},
// Saves the processed image given as data.canvas
// inplace at data.index of data.files:
saveImage: function (data, options) {
if (!data.canvas || options.disabled) {
return data;
}
var that = this,
file = data.files[data.index],
name = file.name,
dfd = $.Deferred(),
callback = function (blob) {
if (!blob.name) {
if (file.type === blob.type) {
blob.name = file.name;
} else if (file.name) {
blob.name = file.name.replace(
/\..+$/,
'.' + blob.type.substr(6)
);
}
}
// Store the created blob at the position
// of the original file in the files list:
data.files[data.index] = blob;
dfd.resolveWith(that, [data]);
};
// Use canvas.mozGetAsFile directly, to retain the filename, as
// Gecko doesn't support the filename option for FormData.append:
if (data.canvas.mozGetAsFile) {
callback(data.canvas.mozGetAsFile(
(/^image\/(jpeg|png)$/.test(file.type) && name) ||
((name && name.replace(/\..+$/, '')) ||
'blob') + '.png',
file.type
));
} else if (data.canvas.toBlob) {
data.canvas.toBlob(callback, file.type);
} else {
return data;
}
return dfd.promise();
},
// Sets the resized version of the image as a property of the
// file object, must be called after "saveImage":
setImage: function (data, options) {
var img = data.canvas || data.img;
if (img && !options.disabled) {
data.files[data.index][options.name] = img;
}
return data;
}
}
});
}));

View File

@@ -0,0 +1,633 @@
/*
* jQuery File Upload User Interface Plugin 8.2.1
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/*jslint nomen: true, unparam: true, regexp: true */
/*global define, window, URL, webkitURL, FileReader */
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define([
'jquery',
'tmpl',
'./jquery.fileupload-resize',
'./jquery.fileupload-validate'
], factory);
} else {
// Browser globals:
factory(
window.jQuery,
window.tmpl
);
}
}(function ($, tmpl, loadImage) {
'use strict';
$.blueimp.fileupload.prototype._specialOptions.push(
'filesContainer',
'uploadTemplateId',
'downloadTemplateId'
);
// The UI version extends the file upload widget
// and adds complete user interface interaction:
$.widget('blueimp.fileupload', $.blueimp.fileupload, {
options: {
// By default, files added to the widget are uploaded as soon
// as the user clicks on the start buttons. To enable automatic
// uploads, set the following option to true:
autoUpload: false,
// The ID of the upload template:
uploadTemplateId: 'template-upload',
// The ID of the download template:
downloadTemplateId: 'template-download',
// The container for the list of files. If undefined, it is set to
// an element with class "files" inside of the widget element:
filesContainer: undefined,
// By default, files are appended to the files container.
// Set the following option to true, to prepend files instead:
prependFiles: false,
// The expected data type of the upload response, sets the dataType
// option of the $.ajax upload requests:
dataType: 'json',
// Function returning the current number of files,
// used by the maxNumberOfFiles validation:
getNumberOfFiles: function () {
return this.filesContainer.children().length;
},
// Callback to retrieve the list of files from the server response:
getFilesFromResponse: function (data) {
if (data.result && $.isArray(data.result.files)) {
return data.result.files;
}
return [];
},
// The add callback is invoked as soon as files are added to the fileupload
// widget (via file input selection, drag & drop or add API call).
// See the basic file upload widget for more information:
add: function (e, data) {
var $this = $(this),
that = $this.data('blueimp-fileupload') ||
$this.data('fileupload'),
options = that.options,
files = data.files;
data.process(function () {
return $this.fileupload('process', data);
}).always(function () {
data.context = that._renderUpload(files).data('data', data);
that._renderPreviews(data);
options.filesContainer[
options.prependFiles ? 'prepend' : 'append'
](data.context);
that._forceReflow(data.context);
that._transition(data.context).done(
function () {
if ((that._trigger('added', e, data) !== false) &&
(options.autoUpload || data.autoUpload) &&
data.autoUpload !== false && !data.files.error) {
data.submit();
}
}
);
});
},
// Callback for the start of each file upload request:
send: function (e, data) {
var that = $(this).data('blueimp-fileupload') ||
$(this).data('fileupload');
if (data.context && data.dataType &&
data.dataType.substr(0, 6) === 'iframe') {
// Iframe Transport does not support progress events.
// In lack of an indeterminate progress bar, we set
// the progress to 100%, showing the full animated bar:
data.context
.find('.progress').addClass(
!$.support.transition && 'progress-animated'
)
.attr('aria-valuenow', 100)
.find('.bar').css(
'width',
'100%'
);
}
return that._trigger('sent', e, data);
},
// Callback for successful uploads:
done: function (e, data) {
var that = $(this).data('blueimp-fileupload') ||
$(this).data('fileupload'),
getFilesFromResponse = data.getFilesFromResponse ||
that.options.getFilesFromResponse,
files = getFilesFromResponse(data),
template,
deferred;
if (data.context) {
data.context.each(function (index) {
var file = files[index] ||
{error: 'Empty file upload result'},
deferred = that._addFinishedDeferreds();
that._transition($(this)).done(
function () {
var node = $(this);
template = that._renderDownload([file])
.replaceAll(node);
that._forceReflow(template);
that._transition(template).done(
function () {
data.context = $(this);
that._trigger('completed', e, data);
that._trigger('finished', e, data);
deferred.resolve();
}
);
}
);
});
} else {
template = that._renderDownload(files)
.appendTo(that.options.filesContainer);
that._forceReflow(template);
deferred = that._addFinishedDeferreds();
that._transition(template).done(
function () {
data.context = $(this);
that._trigger('completed', e, data);
that._trigger('finished', e, data);
deferred.resolve();
}
);
}
},
// Callback for failed (abort or error) uploads:
fail: function (e, data) {
var that = $(this).data('blueimp-fileupload') ||
$(this).data('fileupload'),
template,
deferred;
if (data.context) {
data.context.each(function (index) {
if (data.errorThrown !== 'abort') {
var file = data.files[index];
file.error = file.error || data.errorThrown ||
true;
deferred = that._addFinishedDeferreds();
that._transition($(this)).done(
function () {
var node = $(this);
template = that._renderDownload([file])
.replaceAll(node);
that._forceReflow(template);
that._transition(template).done(
function () {
data.context = $(this);
that._trigger('failed', e, data);
that._trigger('finished', e, data);
deferred.resolve();
}
);
}
);
} else {
deferred = that._addFinishedDeferreds();
that._transition($(this)).done(
function () {
$(this).remove();
that._trigger('failed', e, data);
that._trigger('finished', e, data);
deferred.resolve();
}
);
}
});
} else if (data.errorThrown !== 'abort') {
data.context = that._renderUpload(data.files)
.appendTo(that.options.filesContainer)
.data('data', data);
that._forceReflow(data.context);
deferred = that._addFinishedDeferreds();
that._transition(data.context).done(
function () {
data.context = $(this);
that._trigger('failed', e, data);
that._trigger('finished', e, data);
deferred.resolve();
}
);
} else {
that._trigger('failed', e, data);
that._trigger('finished', e, data);
that._addFinishedDeferreds().resolve();
}
},
// Callback for upload progress events:
progress: function (e, data) {
if (data.context) {
var progress = Math.floor(data.loaded / data.total * 100);
data.context.find('.progress')
.attr('aria-valuenow', progress)
.find('.bar').css(
'width',
progress + '%'
);
}
},
// Callback for global upload progress events:
progressall: function (e, data) {
var $this = $(this),
progress = Math.floor(data.loaded / data.total * 100),
globalProgressNode = $this.find('.fileupload-progress'),
extendedProgressNode = globalProgressNode
.find('.progress-extended');
if (extendedProgressNode.length) {
extendedProgressNode.html(
($this.data('blueimp-fileupload') || $this.data('fileupload'))
._renderExtendedProgress(data)
);
}
globalProgressNode
.find('.progress')
.attr('aria-valuenow', progress)
.find('.bar').css(
'width',
progress + '%'
);
},
// Callback for uploads start, equivalent to the global ajaxStart event:
start: function (e) {
var that = $(this).data('blueimp-fileupload') ||
$(this).data('fileupload');
that._resetFinishedDeferreds();
that._transition($(this).find('.fileupload-progress')).done(
function () {
that._trigger('started', e);
}
);
},
// Callback for uploads stop, equivalent to the global ajaxStop event:
stop: function (e) {
var that = $(this).data('blueimp-fileupload') ||
$(this).data('fileupload'),
deferred = that._addFinishedDeferreds();
$.when.apply($, that._getFinishedDeferreds())
.done(function () {
that._trigger('stopped', e);
});
that._transition($(this).find('.fileupload-progress')).done(
function () {
$(this).find('.progress')
.attr('aria-valuenow', '0')
.find('.bar').css('width', '0%');
$(this).find('.progress-extended').html('&nbsp;');
deferred.resolve();
}
);
},
processstart: function () {
$(this).addClass('fileupload-processing');
},
processstop: function () {
$(this).removeClass('fileupload-processing');
},
// Callback for file deletion:
destroy: function (e, data) {
var that = $(this).data('blueimp-fileupload') ||
$(this).data('fileupload');
if (data.url) {
$.ajax(data).done(function () {
that._transition(data.context).done(
function () {
$(this).remove();
that._trigger('destroyed', e, data);
}
);
});
}
}
},
_resetFinishedDeferreds: function () {
this._finishedUploads = [];
},
_addFinishedDeferreds: function (deferred) {
if (!deferred) {
deferred = $.Deferred();
}
this._finishedUploads.push(deferred);
return deferred;
},
_getFinishedDeferreds: function () {
return this._finishedUploads;
},
// Link handler, that allows to download files
// by drag & drop of the links to the desktop:
_enableDragToDesktop: function () {
var link = $(this),
url = link.prop('href'),
name = link.prop('download'),
type = 'application/octet-stream';
link.bind('dragstart', function (e) {
try {
e.originalEvent.dataTransfer.setData(
'DownloadURL',
[type, name, url].join(':')
);
} catch (ignore) {}
});
},
_formatFileSize: function (bytes) {
if (typeof bytes !== 'number') {
return '';
}
if (bytes >= 1000000000) {
return (bytes / 1000000000).toFixed(2) + ' GB';
}
if (bytes >= 1000000) {
return (bytes / 1000000).toFixed(2) + ' MB';
}
return (bytes / 1000).toFixed(2) + ' KB';
},
_formatBitrate: function (bits) {
if (typeof bits !== 'number') {
return '';
}
if (bits >= 1000000000) {
return (bits / 1000000000).toFixed(2) + ' Gbit/s';
}
if (bits >= 1000000) {
return (bits / 1000000).toFixed(2) + ' Mbit/s';
}
if (bits >= 1000) {
return (bits / 1000).toFixed(2) + ' kbit/s';
}
return bits.toFixed(2) + ' bit/s';
},
_formatTime: function (seconds) {
var date = new Date(seconds * 1000),
days = Math.floor(seconds / 86400);
days = days ? days + 'd ' : '';
return days +
('0' + date.getUTCHours()).slice(-2) + ':' +
('0' + date.getUTCMinutes()).slice(-2) + ':' +
('0' + date.getUTCSeconds()).slice(-2);
},
_formatPercentage: function (floatValue) {
return (floatValue * 100).toFixed(2) + ' %';
},
_renderExtendedProgress: function (data) {
return this._formatBitrate(data.bitrate) + ' | ' +
this._formatTime(
(data.total - data.loaded) * 8 / data.bitrate
) + ' | ' +
this._formatPercentage(
data.loaded / data.total
) + ' | ' +
this._formatFileSize(data.loaded) + ' / ' +
this._formatFileSize(data.total);
},
_renderTemplate: function (func, files) {
if (!func) {
return $();
}
var result = func({
files: files,
formatFileSize: this._formatFileSize,
options: this.options
});
if (result instanceof $) {
return result;
}
return $(this.options.templatesContainer).html(result).children();
},
_renderPreviews: function (data) {
data.context.find('.preview').each(function (index, elm) {
$(elm).append(data.files[index].preview);
});
},
_renderUpload: function (files) {
return this._renderTemplate(
this.options.uploadTemplate,
files
);
},
_renderDownload: function (files) {
return this._renderTemplate(
this.options.downloadTemplate,
files
).find('a[download]').each(this._enableDragToDesktop).end();
},
_startHandler: function (e) {
e.preventDefault();
var button = $(e.currentTarget),
template = button.closest('.template-upload'),
data = template.data('data');
if (data && data.submit && !data.jqXHR && data.submit()) {
button.prop('disabled', true);
}
},
_cancelHandler: function (e) {
e.preventDefault();
var template = $(e.currentTarget).closest('.template-upload'),
data = template.data('data') || {};
if (!data.jqXHR) {
data.errorThrown = 'abort';
this._trigger('fail', e, data);
} else {
data.jqXHR.abort();
}
},
_deleteHandler: function (e) {
e.preventDefault();
var button = $(e.currentTarget);
this._trigger('destroy', e, $.extend({
context: button.closest('.template-download'),
type: 'DELETE'
}, button.data()));
},
_forceReflow: function (node) {
return $.support.transition && node.length &&
node[0].offsetWidth;
},
_transition: function (node) {
var dfd = $.Deferred();
if ($.support.transition && node.hasClass('fade') && node.is(':visible')) {
node.bind(
$.support.transition.end,
function (e) {
// Make sure we don't respond to other transitions events
// in the container element, e.g. from button elements:
if (e.target === node[0]) {
node.unbind($.support.transition.end);
dfd.resolveWith(node);
}
}
).toggleClass('in');
} else {
node.toggleClass('in');
dfd.resolveWith(node);
}
return dfd;
},
_initButtonBarEventHandlers: function () {
var fileUploadButtonBar = this.element.find('.fileupload-buttonbar'),
filesList = this.options.filesContainer;
this._on(fileUploadButtonBar.find('.start'), {
click: function (e) {
e.preventDefault();
filesList.find('.start').click();
}
});
this._on(fileUploadButtonBar.find('.cancel'), {
click: function (e) {
e.preventDefault();
filesList.find('.cancel').click();
}
});
this._on(fileUploadButtonBar.find('.delete'), {
click: function (e) {
e.preventDefault();
filesList.find('.toggle:checked')
.closest('.template-download')
.find('.delete').click();
fileUploadButtonBar.find('.toggle')
.prop('checked', false);
}
});
this._on(fileUploadButtonBar.find('.toggle'), {
change: function (e) {
filesList.find('.toggle').prop(
'checked',
$(e.currentTarget).is(':checked')
);
}
});
},
_destroyButtonBarEventHandlers: function () {
this._off(
this.element.find('.fileupload-buttonbar')
.find('.start, .cancel, .delete'),
'click'
);
this._off(
this.element.find('.fileupload-buttonbar .toggle'),
'change.'
);
},
_initEventHandlers: function () {
this._super();
this._on(this.options.filesContainer, {
'click .start': this._startHandler,
'click .cancel': this._cancelHandler,
'click .delete': this._deleteHandler
});
this._initButtonBarEventHandlers();
},
_destroyEventHandlers: function () {
this._destroyButtonBarEventHandlers();
this._off(this.options.filesContainer, 'click');
this._super();
},
_enableFileInputButton: function () {
this.element.find('.fileinput-button input')
.prop('disabled', false)
.parent().removeClass('disabled');
},
_disableFileInputButton: function () {
this.element.find('.fileinput-button input')
.prop('disabled', true)
.parent().addClass('disabled');
},
_initTemplates: function () {
var options = this.options;
options.templatesContainer = this.document[0].createElement(
options.filesContainer.prop('nodeName')
);
if (tmpl) {
if (options.uploadTemplateId) {
options.uploadTemplate = tmpl(options.uploadTemplateId);
}
if (options.downloadTemplateId) {
options.downloadTemplate = tmpl(options.downloadTemplateId);
}
}
},
_initFilesContainer: function () {
var options = this.options;
if (options.filesContainer === undefined) {
options.filesContainer = this.element.find('.files');
} else if (!(options.filesContainer instanceof $)) {
options.filesContainer = $(options.filesContainer);
}
},
_initSpecialOptions: function () {
this._super();
this._initFilesContainer();
this._initTemplates();
},
_create: function () {
this._super();
this._resetFinishedDeferreds();
},
enable: function () {
var wasDisabled = false;
if (this.options.disabled) {
wasDisabled = true;
}
this._super();
if (wasDisabled) {
this.element.find('input, button').prop('disabled', false);
this._enableFileInputButton();
}
},
disable: function () {
if (!this.options.disabled) {
this.element.find('input, button').prop('disabled', true);
this._disableFileInputButton();
}
this._super();
}
});
}));

View File

@@ -0,0 +1,116 @@
/*
* jQuery File Upload Validation Plugin 1.0.2
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2013, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/*jslint nomen: true, unparam: true, regexp: true */
/*global define, window */
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define([
'jquery',
'./jquery.fileupload-process'
], factory);
} else {
// Browser globals:
factory(
window.jQuery
);
}
}(function ($) {
'use strict';
// Append to the default processQueue:
$.blueimp.fileupload.prototype.options.processQueue.push(
{
action: 'validate',
// Always trigger this action,
// even if the previous action was rejected:
always: true,
// Options taken from the global options map:
acceptFileTypes: '@acceptFileTypes',
maxFileSize: '@maxFileSize',
minFileSize: '@minFileSize',
maxNumberOfFiles: '@maxNumberOfFiles',
disabled: '@disableValidation'
}
);
// The File Upload Validation plugin extends the fileupload widget
// with file validation functionality:
$.widget('blueimp.fileupload', $.blueimp.fileupload, {
options: {
/*
// The regular expression for allowed file types, matches
// against either file type or file name:
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
// The maximum allowed file size in bytes:
maxFileSize: 10000000, // 10 MB
// The minimum allowed file size in bytes:
minFileSize: undefined, // No minimal file size
// The limit of files to be uploaded:
maxNumberOfFiles: 10,
*/
// Function returning the current number of files,
// has to be overriden for maxNumberOfFiles validation:
getNumberOfFiles: $.noop,
// Error and info messages:
messages: {
maxNumberOfFiles: 'Maximum number of files exceeded',
acceptFileTypes: 'File type not allowed',
maxFileSize: 'File is too large',
minFileSize: 'File is too small'
}
},
processActions: {
validate: function (data, options) {
if (options.disabled) {
return data;
}
var dfd = $.Deferred(),
settings = this.options,
file = data.files[data.index],
numberOfFiles = settings.getNumberOfFiles();
if (numberOfFiles && $.type(options.maxNumberOfFiles) === 'number' &&
numberOfFiles + data.files.length > options.maxNumberOfFiles) {
file.error = settings.i18n('maxNumberOfFiles');
} else if (options.acceptFileTypes &&
!(options.acceptFileTypes.test(file.type) ||
options.acceptFileTypes.test(file.name))) {
file.error = settings.i18n('acceptFileTypes');
} else if (options.maxFileSize && file.size > options.maxFileSize) {
file.error = settings.i18n('maxFileSize');
} else if ($.type(file.size) === 'number' &&
file.size < options.minFileSize) {
file.error = settings.i18n('minFileSize');
} else {
delete file.error;
}
if (file.error || data.files.error) {
data.files.error = true;
dfd.rejectWith(this, [data]);
} else {
dfd.resolveWith(this, [data]);
}
return dfd.promise();
}
}
});
}));

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,205 @@
/*
* jQuery Iframe Transport Plugin 1.7
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2011, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/*jslint unparam: true, nomen: true */
/*global define, window, document */
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define(['jquery'], factory);
} else {
// Browser globals:
factory(window.jQuery);
}
}(function ($) {
'use strict';
// Helper variable to create unique names for the transport iframes:
var counter = 0;
// The iframe transport accepts three additional options:
// options.fileInput: a jQuery collection of file input fields
// options.paramName: the parameter name for the file form data,
// overrides the name property of the file input field(s),
// can be a string or an array of strings.
// options.formData: an array of objects with name and value properties,
// equivalent to the return data of .serializeArray(), e.g.:
// [{name: 'a', value: 1}, {name: 'b', value: 2}]
$.ajaxTransport('iframe', function (options) {
if (options.async) {
var form,
iframe,
addParamChar;
return {
send: function (_, completeCallback) {
form = $('<form style="display:none;"></form>');
form.attr('accept-charset', options.formAcceptCharset);
addParamChar = /\?/.test(options.url) ? '&' : '?';
// XDomainRequest only supports GET and POST:
if (options.type === 'DELETE') {
options.url = options.url + addParamChar + '_method=DELETE';
options.type = 'POST';
} else if (options.type === 'PUT') {
options.url = options.url + addParamChar + '_method=PUT';
options.type = 'POST';
} else if (options.type === 'PATCH') {
options.url = options.url + addParamChar + '_method=PATCH';
options.type = 'POST';
}
// javascript:false as initial iframe src
// prevents warning popups on HTTPS in IE6.
// IE versions below IE8 cannot set the name property of
// elements that have already been added to the DOM,
// so we set the name along with the iframe HTML markup:
counter += 1;
iframe = $(
'<iframe src="javascript:false;" name="iframe-transport-' +
counter + '"></iframe>'
).bind('load', function () {
var fileInputClones,
paramNames = $.isArray(options.paramName) ?
options.paramName : [options.paramName];
iframe
.unbind('load')
.bind('load', function () {
var response;
// Wrap in a try/catch block to catch exceptions thrown
// when trying to access cross-domain iframe contents:
try {
response = iframe.contents();
// Google Chrome and Firefox do not throw an
// exception when calling iframe.contents() on
// cross-domain requests, so we unify the response:
if (!response.length || !response[0].firstChild) {
throw new Error();
}
} catch (e) {
response = undefined;
}
// The complete callback returns the
// iframe content document as response object:
completeCallback(
200,
'success',
{'iframe': response}
);
// Fix for IE endless progress bar activity bug
// (happens on form submits to iframe targets):
$('<iframe src="javascript:false;"></iframe>')
.appendTo(form);
window.setTimeout(function () {
// Removing the form in a setTimeout call
// allows Chrome's developer tools to display
// the response result
form.remove();
}, 0);
});
form
.prop('target', iframe.prop('name'))
.prop('action', options.url)
.prop('method', options.type);
if (options.formData) {
$.each(options.formData, function (index, field) {
$('<input type="hidden"/>')
.prop('name', field.name)
.val(field.value)
.appendTo(form);
});
}
if (options.fileInput && options.fileInput.length &&
options.type === 'POST') {
fileInputClones = options.fileInput.clone();
// Insert a clone for each file input field:
options.fileInput.after(function (index) {
return fileInputClones[index];
});
if (options.paramName) {
options.fileInput.each(function (index) {
$(this).prop(
'name',
paramNames[index] || options.paramName
);
});
}
// Appending the file input fields to the hidden form
// removes them from their original location:
form
.append(options.fileInput)
.prop('enctype', 'multipart/form-data')
// enctype must be set as encoding for IE:
.prop('encoding', 'multipart/form-data');
}
form.submit();
// Insert the file input fields at their original location
// by replacing the clones with the originals:
if (fileInputClones && fileInputClones.length) {
options.fileInput.each(function (index, input) {
var clone = $(fileInputClones[index]);
$(input).prop('name', clone.prop('name'));
clone.replaceWith(input);
});
}
});
form.append(iframe).appendTo(document.body);
},
abort: function () {
if (iframe) {
// javascript:false as iframe src aborts the request
// and prevents warning popups on HTTPS in IE6.
// concat is used to avoid the "Script URL" JSLint error:
iframe
.unbind('load')
.prop('src', 'javascript'.concat(':false;'));
}
if (form) {
form.remove();
}
}
};
}
});
// The iframe transport returns the iframe content document as response.
// The following adds converters from iframe to text, json, html, xml
// and script.
// Please note that the Content-Type for JSON responses has to be text/plain
// or text/html, if the browser doesn't include application/json in the
// Accept header, else IE will show a download dialog.
// The Content-Type for XML responses on the other hand has to be always
// application/xml or text/xml, so IE properly parses the XML response.
// See also
// https://github.com/blueimp/jQuery-File-Upload/wiki/Setup#content-type-negotiation
$.ajaxSetup({
converters: {
'iframe text': function (iframe) {
return iframe && $(iframe[0].body).text();
},
'iframe json': function (iframe) {
return iframe && $.parseJSON($(iframe[0].body).text());
},
'iframe html': function (iframe) {
return iframe && $(iframe[0].body).html();
},
'iframe xml': function (iframe) {
var xmlDoc = iframe && iframe[0];
return xmlDoc && $.isXMLDoc(xmlDoc) ? xmlDoc :
$.parseXML((xmlDoc.XMLDocument && xmlDoc.XMLDocument.xml) ||
$(xmlDoc.body).html());
},
'iframe script': function (iframe) {
return iframe && $.globalEval($(iframe[0].body).text());
}
}
});
}));

View File

@@ -0,0 +1,485 @@
$(function(){
var csrfToken = getCookie('csrftoken'),
widget = $('.files-widget'),
effectTime = 200,
mediaURL = $('[data-media-url]').data('media-url'),
staticURL = $('[data-static-url]').data('static-url'),
thumbnailURL = $('[data-get-thumbnail-url]').data('get-thumbnail-url'),
undoText = $('[data-undo-text]').data('undo-text'),
template,
deletedTemplate;
template =
'<div class="new preview">'+
'<span class="image-holder">'+
'<img class="thumbnail" />'+
'<span class="buttons">'+
'<a href="javascript:void(0)" class="enlarge-button">'+
'<img src="'+ staticURL + 'files_widget/img/enlarge_button.png" />'+
'</a> '+
'<a href="javascript:void(0)" class="remove-button">'+
'<img src="'+ staticURL + 'files_widget/img/close_button.png" />'+
'</a>'+
'</span>'+
'</span>'+
'<div class="progress-holder">'+
'<div class="progress"></div>'+
'</div>'+
'</div>';
deletedTemplate =
'<div class="deleted-file">'+
'<span class="image-holder">'+
'<img class="icon" />'+
'</span>'+
'<span class="name"></span>'+
'<span class="undo">'+
'<a href="javascript:void(0);" class="undo-remove-button">'+
undoText+
'</a>'+
'</span>'+
'</div>';
function splitlines(str) {
return str.match(/[^\r\n]+/g) || [];
}
function filenameFromPath(path) {
return path.replace(/^.+\//, '');
}
function stripMediaURL(path) {
if (path.indexOf(mediaURL) === 0) {
return path.replace(mediaURL, '');
}
return path;
}
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function numberformat( number, decimals, dec_point, thousands_sep ) {
// http://kevin.vanzonneveld.net
// + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// * example 1: number_format(1234.5678, 2, '.', '');
// * returns 1: 1234.57
var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
var d = dec_point == undefined ? "," : dec_point;
var t = thousands_sep == undefined ? "." : thousands_sep, s = n < 0 ? "-" : "";
var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}
function sizeformat(filesize, bits) {
var b = 'B';
if (bits) {
b = 'b';
}
// from http://snipplr.com/view/5945/javascript-numberformat--ported-from-php/
if (filesize >= 1073741824) {
filesize = numberformat(filesize / 1073741824, 2, '.', '') + 'G' + b;
} else {
if (filesize >= 1048576) {
filesize = numberformat(filesize / 1048576, 2, '.', '') + 'M' + b;
} else {
if (filesize >= 1024) {
filesize = numberformat(filesize / 1024, 0) + 'k' + b;
} else {
filesize = numberformat(filesize, 0) + b;
};
};
};
return filesize;
};
function fillIn(input, files) {
var value = '';
files.each(function() {
var path = $(this).data('image-path');
if (path) {
value += path + '\n';
}
});
input.val(value);
}
function fillInHiddenInputs(dropbox, movedOutFile, movedInFile) {
var input = $('input[name="' + dropbox.data('input-name') + '_0"]'),
deletedInput = $('input[name="' + dropbox.data('input-name') + '_1"]'),
movedInput = $('input[name="' + dropbox.data('input-name') + '_2"]'),
widget = input.closest('.files-widget'),
files = widget.find('.preview'),
deletedFiles = widget.find('.deleted-file');
fillIn(input, files.add(movedInFile));
fillIn(deletedInput, deletedFiles);
if (movedOutFile) {
var movedInputValue = splitlines(movedInput.val()),
filename = movedOutFile.data('image-path');
movedInputValue.push(filename);
movedInput.val(movedInputValue.join('\n'));
}
if (movedInFile) {
var movedInputValue = splitlines(movedInput.val()),
filename = movedInFile.data('image-path'),
index = movedInputValue.indexOf(filename);
if (index != -1) {
movedInputValue.splice(index, 1);
movedInput.val(movedInputValue);
}
}
}
function downloadThumbnail(preview) {
var imagePath = stripMediaURL(preview.data('image-path')),
dropbox = preview.closest('.files-widget-dropbox'),
previewSize = dropbox.data('preview-size');
$.get(thumbnailURL,
'img=' + encodeURIComponent(imagePath) + '&preview_size=' + previewSize,
function(data) {
preview.find('.thumbnail')
.css({ 'width': '', 'height': '' }).attr('src', data);
preview.removeClass('new');
});
}
function generateThumbnail(preview, file) {
var image = $('.thumbnail', preview),
reader = new FileReader(),
dropbox = preview.closest('.files-widget-dropbox'),
previewSize = dropbox.data('preview-size'),
defaultSize = parseInt(+previewSize * 2 / 3, 10);
reader.onload = function(e) {
image.attr('src', e.target.result);
image.css({ 'width': '', 'height': '' });
};
image.css({
'max-width': previewSize, 'max-height': previewSize,
'width': defaultSize, 'height': defaultSize
});
if (file.size < 500000) {
reader.readAsDataURL(file);
} else {
$('<span/>').addClass('filename').text(file.name)
.appendTo(preview.find('.image-holder'));
}
}
function addPreview(dropbox, imagePath, thumbnailPath, file, fromHiddenInput) {
var preview = $(template);
if (dropbox.data('multiple') != 1) {
dropbox.find('.preview').each(function() {
deletePreview($(this), true);
});
}
dropbox.find('.message').hide();
preview.hide().insertAfter(dropbox.children(':last-child')).fadeIn(effectTime);
if (imagePath) {
completePreview(preview, imagePath, thumbnailPath, fromHiddenInput);
} else if (file) {
generateThumbnail(preview, file);
}
return preview;
}
function completePreview(preview, imagePath, thumbnailPath, fromHiddenInput) {
var dropbox = preview.closest('.files-widget-dropbox');
preview.removeClass('new').attr('data-image-path', imagePath);
preview.find('.progress-holder, .filename').remove();
if (thumbnailPath) {
preview.find('.thumbnail')
.css({ 'width': '', 'height': '' }).attr('src', thumbnailPath);
} else {
downloadThumbnail(preview);
}
if (!fromHiddenInput) {
fillInHiddenInputs(dropbox);
}
}
function onPreviewMove(preview, oldDropbox, newDropbox) {
if (oldDropbox.is(newDropbox)) {
fillInHiddenInputs(oldDropbox);
} else {
if (newDropbox.data('multiple') != 1) {
newDropbox.find('.preview').not(preview).each(function() {
deletePreview($(this), true);
});
}
fillInHiddenInputs(oldDropbox, preview, null);
fillInHiddenInputs(newDropbox, null, preview);
if (!oldDropbox.find('.preview').length) {
oldDropbox.find('.message').show();
}
if (oldDropbox.data('preview-size') !== newDropbox.data('preview-size')) {
downloadThumbnail(preview);
}
}
}
function deletePreview(preview, changingToNewPreview) {
var dropbox = preview.closest('.files-widget-dropbox'),
widget = dropbox.closest('.files-widget'),
deletedPreview = $(deletedTemplate),
deletedContainer = $('.files-widget-deleted', widget),
deletedList = $('.deleted-list', deletedContainer),
path = preview.data('image-path');
function doDelete() {
$('.icon', deletedPreview).attr('src', preview.find('.thumbnail').attr('src'));
$('.name', deletedPreview).text(filenameFromPath(path));
deletedPreview.attr('data-image-path', path);
deletedContainer.show();
deletedPreview.hide().appendTo(deletedList)
deletedPreview.slideDown(effectTime);
preview.remove();
if (!dropbox.find('.preview').length && !changingToNewPreview) {
dropbox.find('.message').show();
};
fillInHiddenInputs(dropbox);
}
if (changingToNewPreview) {
doDelete();
} else {
preview.fadeOut(effectTime, doDelete);
}
}
function undoDeletePreview(deletedPreview) {
var imagePath = deletedPreview.data('image-path'),
thumbnailPath = $('.icon', deletedPreview).attr('src'),
widget = deletedPreview.closest('.files-widget'),
dropbox = widget.find('.files-widget-dropbox'),
deletedContainer = $('.files-widget-deleted', widget),
deletedList = $('.deleted-list', deletedContainer),
preview = addPreview(dropbox, imagePath, thumbnailPath);
deletedPreview.slideUp(effectTime, function() {
$(this).remove();
if (!deletedList.find('.deleted-file').length) {
deletedContainer.hide();
};
fillInHiddenInputs(dropbox);
});
}
$(document).bind('drag dragover', function (e) {
e.preventDefault();
$('.files-widget-dropbox').addClass('dragging-files');
}).bind('drop', function (e) {
e.preventDefault();
$('.files-widget-dropbox').removeClass('dragging-files');
}).bind('dragleave', function (e) {
$('.files-widget-dropbox').removeClass('dragging-files');
});
widget.each(function() {
var that = $(this),
dropbox = $('.files-widget-dropbox', that),
filesInput = $('.files-input', that),
message = $('.message', dropbox),
uploadURL = dropbox.data('upload-url'),
multiple = dropbox.data('multiple') == 1,
previewSize = dropbox.data('preview-size'),
initialFiles = $('.preview', dropbox),
fileBrowserResultInput = $('.filebrowser-result', that),
deletedContainer = $('.files-widget-deleted', that),
deletedList = $('.deleted-list', deletedContainer),
stats = $('.upload-progress-stats', that),
hiddenInput = $('input[name="' + dropbox.data('input-name') + '_0"]'),
initialFileNames = splitlines(hiddenInput.val()),
name;
for (name in initialFileNames) {
if (!initialFiles.filter('[data-image-path="' + initialFileNames[name] + '"]').length) {
addPreview(dropbox, initialFileNames[name], null, null, true);
}
}
initialFiles = $('.preview', dropbox);
if (initialFiles.length) {
message.hide();
}
if (deletedList.find('.deleted-file').length) {
deletedContainer.show();
}
dropbox.on('click', '.remove-button', function() {
var preview = $(this).closest('.preview');
deletePreview(preview);
});
that.on('click', '.undo-remove-button', function() {
var deletedPreview = $(this).closest('.deleted-file');
undoDeletePreview(deletedPreview);
});
dropbox.on('click', '.enlarge-button', function() {
window.open(mediaURL + $(this).closest('.preview').data('image-path'));
});
function onFileBrowserResult() {
var imagePath = stripMediaURL(fileBrowserResultInput.val()),
preview = addPreview(dropbox, imagePath);
fileBrowserResultInput.val('');
}
function checkFileBrowserResult() {
var oldVal = fileBrowserResultInput.val(),
checkInterval;
checkInterval = setInterval(function() {
var newVal = fileBrowserResultInput.val();
if (oldVal != newVal) {
clearInterval(checkInterval);
onFileBrowserResult();
}
}, 250);
}
$('.media-library-button', that).on('click', function() {
var url = window.__filebrowser_url || '/admin/media-library/browse/'
FileBrowser.show(fileBrowserResultInput.attr('id'), url + '?pop=1');
checkFileBrowserResult();
});
$('.add-by-url-button', that).on('click', function() {
$('.add-by-url-container', that).show();
$(this).hide();
$('.add-by-url', that).trigger('focus');
});
$('.add-by-url', that).on('focusout', function() {
$('.add-by-url-button', that).show();
$('.add-by-url-container', that).hide();
}).on('keypress', function (e) {
var urlInput = $(this),
val = urlInput.val();
if (e.which == 13) {
e.stopPropagation();
e.preventDefault();
$('.add-by-url-button', that).show();
$('.add-by-url-container', that).hide();
urlInput.val('');
if (val.length) {
addPreview(dropbox, val);
}
return false;
}
});
dropbox.disableSelection();
dropbox.bind('dragover', function (e) {
dropbox.addClass('dragover');
}).bind('dragleave drop', function (e) {
dropbox.removeClass('dragover');
});
dropbox.sortable({
placeholder: 'sortable-placeholder',
//tolerance: 'pointer',
connectWith: '.files-widget-dropbox',
//cursorAt: { top: 0, left: 0 },
//items: '.preview:not(.controls-preview)',
revert: effectTime,
start: function(e, ui) {
$('.sortable-placeholder').width(ui.item.width()).height(ui.item.height());
},
over: function() {
message.hide();
},
beforeStop: function(e, ui) {
var newDropbox = ui.placeholder.closest('.files-widget-dropbox');
onPreviewMove(ui.item, dropbox, newDropbox);
}
});
filesInput.fileupload({
url: uploadURL,
type: 'POST',
dataType: 'json',
dropZone: dropbox,
pasteZone: dropbox,
paramName: 'files[]',
limitConcurrentUploads: 3,
formData: [
{ name: 'csrfmiddlewaretoken', value: csrfToken },
{ name: 'preview_size', value: previewSize }
],
autoUpload: true,
maxFileSize: 10000000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
maxNumberOfFiles: undefined,
previewMaxWidth: 150,
previewMaxHeight: 150,
previewCrop: true,
add: function(e, data) {
var preview = addPreview(dropbox, undefined, undefined, data.files[0]);
data.context = preview;
data.submit();
},
submit: function(e, data) {
// console.log('submit', data);
// create thumbnail client side?
},
done: function(e, data) {
completePreview(data.context,
data.result.imagePath, data.result.thumbnailPath);
},
fail: function(e, data) {
//console.log('failed', data);
// display errors
},
always: function(e, data) {
//console.log('always', data);
stats.text('');
},
progress: function(e, data) {
//console.log('progress', data);
var progress = parseInt(data.loaded / data.total * 100, 10);
data.context.find('.progress').css('width', progress + '%');
},
progressall: function(e, data) {
//console.log('progressall', data);
stats.text(sizeformat(data.loaded) +
' of ' + sizeformat(data.total) +
' (' + sizeformat(data.bitrate, true) + 'ps)');
},
});
});
});

View File

@@ -0,0 +1,91 @@
{% load i18n files_widget_tags %}
<div class="files-widget">
<div class="files-widget-dropbox" id="{{ name }}-dropbox" data-input-name="{{ name }}" data-upload-url="{% url 'files_widget_upload' %}" data-get-thumbnail-url="{% url 'files_widget_get_thumbnail_url' %}" data-media-url="{{ MEDIA_URL }}" data-static-url="{{ STATIC_URL }}" data-multiple="{{ multiple }}" data-preview-size="{{ preview_size }}" data-undo-text="{% trans 'undo' %}">
<span class="message">
{% if multiple %}
{% trans 'Drop multiple images here to upload' %}
{% else %}
{% trans 'Drop an image here to upload' %}
{% endif %}
</span>
{% for path_to_file in files.splitlines %}{% spaceless %}
<div class="preview filetype" data-image-path="{{ path_to_file }}">
<div class="image-holder icon30">
{% if path_to_file|is_image %}
<img class="thumbnail icon30" src="{% include 'files_widget/includes/thumbnail.html' %}" />
{% else %}
<img class="thumbnail icon30" src="{{ STATIC_URL }}files_widget/img/file-icons/file_icon.png" />
{% endif %}
</div>
<div class="file-name-for-icon30" title="{{ path_to_file|filename_from_path }}">
{{ path_to_file|filename_from_path }}
</div>
<span class="buttons">
<a href="javascript:void(0)" class="enlarge-button">
<img src="{{ STATIC_URL }}files_widget/img/enlarge_button.png" />
</a>
<a href="javascript:void(0)" class="remove-button">
<img src="{{ STATIC_URL }}files_widget/img/close_button.png" />
</a>
</span>
</div>
{% endspaceless %}{% endfor %}
</div>
<div class="controls">
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<a href="javascript:void(0)" class="fake-files-input">
<span>{% trans 'Upload' %}...</span>
<input type="file" class="files-input" id="{{ name }}-files" multiple="mulitple" />
</a>
{% if use_filebrowser %}
&nbsp;|&nbsp;
<a href="javascript:void(0)" class="media-library-button">{% trans 'Library' %}</a>
{% endif %}
{% if add_image_by_url %}
&nbsp;|&nbsp;
<a href="javascript:void(0)" class="add-by-url-button">{% trans 'Add by url...' %}</a>
<span class="add-by-url-container" style="display: none">
<input type="text" class="add-by-url" placeholder="{% trans 'Add by url...' %}" />
</span>
{% endif %}
{{ input_string }}
{# here comes the hacked mezzanine-filebrowser-safe integration #}
<span class="hacked-filebrowser-integration" style="display: none !important;">
<input type="hidden" id="{{ name }}-filebrowser-result" class="filebrowser-result" />
<img id="image_{{ name }}-filebrowser-result" />
<a id="link_{{ name }}-filebrowser-result"></a>
<img id="previewimage_{{ name }}-filebrowser-result" />
<a id="previewlink_{{ name }}-filebrowser-result"></a>
<span id="help_{{ name }}-filebrowser-result"></span>
<span id="preview_{{ name }}-filebrowser-result"></span>
</span>
<span class="upload-progress-stats"></span>
</div>
<div class="files-widget-deleted" style="display: none">
<p>{% trans 'Images to be removed' %}:</p>
<div class="deleted-list">
{% for path_to_file in deleted_files.splitlines %}
<div class="deleted-file" data-image-path="{{ path_to_file }}">
<span class="image-holder">
{% if path_to_file|is_image %}
<img class="icon" src="{% include 'files_widget/includes/thumbnail.html' %}" />
{% else %}
{# {% include 'files_widget/includes/file.html' %}#}
<img class="icon" src="{{ STATIC_URL }}files_widget/img/file-icons/file_icon.png" />
{% endif %}
{# <img class="icon" src="{% include 'files_widget/includes/thumbnail.html' %}" />#}
</span>
<span class="name">{{ path_to_file|filename_from_path }}</span>
<span class="undo">
<a href="javascript:void(0);" class="undo-remove-button">
Undo
</a>
</span>
</div>
{% endfor %}
</div>
</div>
</div>

View File

@@ -0,0 +1,90 @@
{% load i18n files_widget_tags %}
<div class="files-widget">
<div class="files-widget-dropbox" id="{{ name }}-dropbox" data-input-name="{{ name }}" data-upload-url="{% url 'files_widget_upload' %}" data-get-thumbnail-url="{% url 'files_widget_get_thumbnail_url' %}" data-media-url="{{ MEDIA_URL }}" data-static-url="{{ STATIC_URL }}" data-multiple="{{ multiple }}" data-preview-size="{{ preview_size }}" data-undo-text="{% trans 'undo' %}">
<span class="message">
{% if multiple %}
{% trans 'Drop multiple images here to upload' %}
{% else %}
{% trans 'Drop an image here to upload' %}
{% endif %}
</span>
{% for path_to_file in files.splitlines %}{% spaceless %}
<div class="preview" data-image-path="{{ path_to_file }}">
<div class="image-holder icon100">
{% if path_to_file|is_image %}
<img class="thumbnail icon100" src="{% include 'files_widget/includes/thumbnail.html' %}" />
{% else %}
<img class="thumbnail icon100" src="{{ STATIC_URL }}files_widget/img/file-icons/file_icon.png" />
{% endif %}
<span class="buttons">
<a href="javascript:void(0)" class="enlarge-button">
<img src="{{ STATIC_URL }}files_widget/img/enlarge_button.png" />
</a>
<a href="javascript:void(0)" class="remove-button">
<img src="{{ STATIC_URL }}files_widget/img/close_button.png" />
</a>
</span>
</div>
<div class="file-name-for-icon100" title="{{ path_to_file|filename_from_path }}">
{{ path_to_file|filename_from_path }}
</div>
</div>
{% endspaceless %}{% endfor %}
</div>
<div class="controls">
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<a href="javascript:void(0)" class="fake-files-input">
<span>{% trans 'Upload' %}...</span>
<input type="file" class="files-input" id="{{ name }}-files" multiple="mulitple" />
</a>
{% if use_filebrowser %}
&nbsp;|&nbsp;
<a href="javascript:void(0)" class="media-library-button">{% trans 'Library' %}</a>
{% endif %}
{% if add_image_by_url %}
&nbsp;|&nbsp;
<a href="javascript:void(0)" class="add-by-url-button">{% trans 'Add by url...' %}</a>
<span class="add-by-url-container" style="display: none">
<input type="text" class="add-by-url" placeholder="{% trans 'Add by url...' %}" />
</span>
{% endif %}
{{ input_string }}
{# here comes the hacked mezzanine-filebrowser-safe integration #}
<span class="hacked-filebrowser-integration" style="display: none !important;">
<input type="hidden" id="{{ name }}-filebrowser-result" class="filebrowser-result" />
<img id="image_{{ name }}-filebrowser-result" />
<a id="link_{{ name }}-filebrowser-result"></a>
<img id="previewimage_{{ name }}-filebrowser-result" />
<a id="previewlink_{{ name }}-filebrowser-result"></a>
<span id="help_{{ name }}-filebrowser-result"></span>
<span id="preview_{{ name }}-filebrowser-result"></span>
</span>
<span class="upload-progress-stats"></span>
</div>
<div class="files-widget-deleted" style="display: none">
<p>{% trans 'Images to be removed' %}:</p>
<div class="deleted-list">
{% for path_to_file in deleted_files.splitlines %}
<div class="deleted-file" data-image-path="{{ path_to_file }}">
<span class="image-holder">
{% if path_to_file|is_image %}
<img class="icon" src="{% include 'files_widget/includes/thumbnail.html' %}" />
{% else %}
<img class="icon" src="{{ STATIC_URL }}files_widget/img/file-icons/file_icon.png" />
{% endif %}
{# <img class="icon" src="{% include 'files_widget/includes/thumbnail.html' %}" />#}
</span>
<span class="name">{{ path_to_file|filename_from_path }}</span>
<span class="undo">
<a href="javascript:void(0);" class="undo-remove-button">
Undo
</a>
</span>
</div>
{% endfor %}
</div>
</div>
</div>

View File

@@ -0,0 +1,10 @@
{% load i18n files_widget_tags %}
<div class="preview filetype" data-image-path="{{ path_to_file }}">
<div class="image-holder30">
<img class="thumbnail30" src="{{ STATIC_URL }}files_widget/img/file-icons/file_icon.png" />
</div>
<div class="file-name-for-icon30" title="{{ path_to_file|filename_from_path }}">
{{ path_to_file|filename_from_path }}
</div>
</div>

View File

@@ -0,0 +1 @@
{% load thumbnail files_widget_tags %}{% thumbnail path_to_file|unquote preview_size|add:'x'|add:preview_size upscale=False format=path_to_file|thumbnail_format as thumb %}{{ thumb.url }}{% endthumbnail %}

View File

View File

@@ -0,0 +1,46 @@
import re
from six.moves import urllib
from django import template
register = template.Library()
@register.tag
def sorl_thumbnail(parser, token):
from sorl.thumbnail.templatetags.thumbnail import thumbnail
try:
res = thumbnail(parser, token)
except Exception as e:
res = None
print('1')
return res
@register.filter
def is_image(path):
from ..files import is_file_image
from tEDataProj.settings import MEDIA_ROOT
path = f'{MEDIA_ROOT}{path}'
return is_file_image(path)
@register.filter
def thumbnail_format(path):
match = re.search(r'\.\w+$', path)
if match:
ext = match.group(0)
if ext.lower() in ['.gif', '.png']:
return 'PNG'
return 'JPEG'
@register.filter
def filename_from_path(path):
path = re.sub(r'^.+\/', '', path)
path = re.sub(r'^.+\\', '', path)
return path
@register.filter
def unquote(value):
"urldecode"
return urllib.parse.unquote(value)

12
files_widget/urls.py Normal file
View File

@@ -0,0 +1,12 @@
try:
from django.conf.urls.defaults import url
except:
from django.conf.urls import url
from django.conf import settings
from .views import upload, thumbnail_url
urlpatterns = [
url(u'^upload/$', upload, name="files_widget_upload"),
url(u'^thumbnail-url/$', thumbnail_url, name="files_widget_get_thumbnail_url"),
]

5
files_widget/utils.py Normal file
View File

@@ -0,0 +1,5 @@
from functools import partial
def curry(func, *a, **kw):
return partial(func, *a, **kw)

71
files_widget/views.py Normal file
View File

@@ -0,0 +1,71 @@
import json
from django.http import Http404, HttpResponse, HttpResponseBadRequest
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.template.loader import render_to_string
from django.contrib.auth.decorators import permission_required
from .files import save_upload, is_file_image
from .controllers import FilePath, ImagePath
# @permission_required('files_widget.can_upload_files')
def upload(request):
if not request.method == 'POST':
raise Http404
# if request.is_ajax():
# # the file is stored raw in the request
# upload = request
# is_raw = True
# # AJAX Upload will pass the filename in the querystring if it is the "advanced" ajax upload
# try:
# filename = request.GET['files[0]']
# except KeyError:
# return HttpResponseBadRequest(json.dumps({
# 'success': False,
# 'message': 'Error while uploading file',
# }))
# not an ajax upload, so it was the "basic" iframe version with submission via form
# else:
is_raw = False
try:
upload = next(iter(request.FILES.values()))
except StopIteration:
return HttpResponseBadRequest(json.dumps({
'success': False,
'message': 'Error while uploading file.',
}))
filename = upload.name
path_to_file = save_upload(upload, filename, is_raw, request.user)
MEDIA_URL = settings.MEDIA_URL
if 'preview_size' in request.POST:
preview_size = request.POST['preview_size']
else:
preview_size = '64'
if not is_file_image(f'{settings.MEDIA_ROOT}{path_to_file}'):
thumbnailPath = f'{settings.STATIC_URL}files_widget/img/file-icons/file_icon.png'
else:
thumbnailPath = render_to_string('files_widget/includes/thumbnail.html', locals())
return HttpResponse(json.dumps({
'success': True,
'imagePath': path_to_file,
'thumbnailPath': thumbnailPath,
}))
# @permission_required('files_widget.can_upload_files')
def thumbnail_url(request):
try:
if not 'img' in request.GET or not 'preview_size' in request.GET:
raise Http404
thumbnail_url = ImagePath(request.GET['img']).thumbnail(request.GET['preview_size']).url
except:
thumbnail_url = 'files_widget/static/files_widget/img/file-icons/file_icon.png'
return HttpResponse(thumbnail_url)