Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 30 additions & 4 deletions uploadify/templates/uploadify/multi_file_upload.html
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
<script type="text/javascript" src="{{ uploadify_path }}swfobject.js"></script>
<script type="text/javascript" src="{{ uploadify_path }}jquery.uploadify.js"></script>
<div id="uploadify" class="multi_file_upload"><input id="fileInput" name="fileInput" type="file" /></div>
<link rel="stylesheet" type="text/css" href="{{ uploadify_path }}uploadify.css" />
<div id="uploadify" class="multi_file_upload">
<input id="fileInput" name="fileInput" type="file" />
{% if not uploadify_auto %}
<input type="button" value="Upload" id="upload" />
{% endif %}
</div>
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { //test for MSIE x.x;
Expand All @@ -10,14 +16,19 @@
}
$('#fileInput').uploadify({
'uploader': '{{ uploadify_path }}uploadify.swf',
'script': '{% url uploadify_upload %}{{ GET_query }}',
'script': '{% url uploadify_upload %}{{ uploadify_query }}',
'scriptData': {{ uploadify_data|safe }},
'cancelImg': '{{ uploadify_path }}cancel.png',
'auto': true,
'removeCompleted': false,
'multi': true,
'onAllComplete': uploadify_allComplete,
'onCancel': uploadify_cancelUpload,
'onComplete': uploadify_complete
'onComplete': uploadify_complete,
{{ uploadify_options|safe }}
});

$('#upload').click(function(){
$('#fileInput').uploadifyUpload();
});
});

Expand All @@ -28,6 +39,21 @@
$('#uploadify').trigger('cancelUpload', data);
}
function uploadify_complete(event, ID, fileObj, response, data) {
if (response!='1'){
response = eval('(' +response +')');

var file_div = jQuery("#" + jQuery(event.target).attr('id') + ID);
file_div.addClass('error');

var file_percentage = file_div.find('.percentage');
file_percentage.text(' -');
$(response.{{ uploadify_filename|safe }}).each(function(){
file_percentage.text(file_percentage.text()+" "+this);
});

return false;
}
$('#uploadify').trigger('complete', [ID, fileObj, response, data]);
$('#upload').hide();
}
// ]]></script>
74 changes: 64 additions & 10 deletions uploadify/templatetags/uploadify_tags.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,76 @@
from django import template
from uploadify import settings
from django.utils import simplejson

register = template.Library()

# -----------------------------------------------------------------------------
# multi_file_upload
# -----------------------------------------------------------------------------
@register.inclusion_tag('uploadify/multi_file_upload.html', takes_context=True)
def multi_file_upload(context, unique_id=None):
class MultiFileUpload(template.Node):
def __init__(self, sender='uploadify', unique_id=None, options={}, data={}):
self.sender = sender
self.unique_id = unique_id
self.options = {'fileDataName': 'Filedata'}
self.options.update(options)
self.data = {'fileDataName': self.options['fileDataName'],
'sender': str(self.sender)}
self.data.update(data)

def render(self, context):
if self.unique_id is not None:
unique_id = "?unique_id=%s" % str(self.unique_id)
else:
unique_id = ""

js_options = ",".join(map(lambda k: "'%s': '%s'" % (k, self.options[k]),
self.options))

auto = False
if self.options.has_key('auto') and self.options['auto']:
auto = True

context.update({
'uploadify_query': unique_id,
'uploadify_data': simplejson.dumps(self.data),
'uploadify_path': settings.UPLOADIFY_PATH,
'uploadify_options': js_options,
'uploadify_filename': self.options['fileDataName'],
'uploadify_auto': auto,
})

t = template.loader.get_template('uploadify/multi_file_upload.html')
return t.render(context)


@register.tag
def multi_file_upload(parser, token):
"""
Displays a Flash-based interface for uploading multiple files.
For each POST request (after file upload) send GET query with `unique_id`.

{% multi_file_upload sender='SomeThing' fileDataName='Filename' %}

For all options see http://www.uploadify.com/documentation/

"""
if unique_id is not None:
GET_query = '?unique_id=' + str(unique_id)
else:
GET_query = ''
return {
'GET_query' : GET_query,
'uploadify_path' : settings.UPLOADIFY_PATH,
}
args = token.split_contents()
tag_name = args[0]
args = args[1:]

sender = 'uploadify'
unique_id = None
options = {}

for arg in args:
name, val = arg.split("=")
val = val.replace('\'', '').replace('"', '')
if name == 'sender':
sender = val
elif name == 'unique_id':
unique_id = val
else:
options[name] = val

return MultiFileUpload(sender, unique_id, options)

15 changes: 12 additions & 3 deletions uploadify/views.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,23 @@
from django.dispatch import Signal
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from sugar.views.json import JsonResponse

upload_received = Signal(providing_args=['request', 'data'])

@csrf_exempt
def upload(request, *args, **kwargs):
if request.method == 'POST':
sender='uploadify'
filename = 'Filename'
if request.POST.has_key('sender'):
sender = request.POST['sender']
if request.POST.has_key('fileDataName'):
filename = request.POST['fileDataName']
if request.FILES:
file_url = upload_received.send(sender='uploadify', request=request,
data=request.FILES['Filedata'])[-1][1]
return HttpResponse(file_url)
receiveds = upload_received.send(sender=sender, request=request,
data=request.FILES[filename])
for received, response in receiveds:
if not response is None:
return JsonResponse(response)
return HttpResponse('1')
47 changes: 47 additions & 0 deletions uploadify/widgets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# -*- coding: utf-8 -*-

from uploadify import settings
from django.contrib.admin.widgets import AdminFileWidget
from uploadify.templatetags.uploadify_tags import MultiFileUpload
from django.utils.safestring import mark_safe
from django.template import Context

class UploadifyAdminWidget(AdminFileWidget):
"""
Create uploadify widget. It receive:
'sender' - string (default = uploadify)
'unique_id'
'options' - http://www.uploadify.com/documentation/
'data' - POST data

Example:
self.fields['uploadify'].widget = UploadifyAdminWidget(
attrs={'data': post_data, 'options': {'fileDataName': 'image'}})
"""

js = """
<script type="text/javascript">
$('#uploadify').bind('allUploadsComplete', function(data){
window.location.reload();
});
</script>"""

def __init__(self, *args, **kwargs):
self.sender = 'uploadify'
self.unique_id = None
self.options = {}
self.data = {}

if kwargs.has_key('attrs'):
for attr in kwargs['attrs']:
if attr in ('sender', 'unique_id', 'options', 'data'):
setattr(self, attr, kwargs['attrs'][attr])
super(UploadifyAdminWidget, self).__init__(*args, **kwargs)

def render(self, name, value, attrs=None):
context = Context({})
uploader = MultiFileUpload(self.sender, self.unique_id, self.options, self.data)
template_data = uploader.render(context)
template_data += self.js

return mark_safe(template_data)