Skip to content

Commit 24a73d2

Browse files
committed
Merge pull request #1 from smacker/master.
More configurable and widget
2 parents 9e179ef + 5af9b5c commit 24a73d2

File tree

4 files changed

+153
-17
lines changed

4 files changed

+153
-17
lines changed

uploadify/templates/uploadify/multi_file_upload.html

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
<script type="text/javascript" src="{{ uploadify_path }}swfobject.js"></script>
22
<script type="text/javascript" src="{{ uploadify_path }}jquery.uploadify.js"></script>
3-
<div id="uploadify" class="multi_file_upload"><input id="fileInput" name="fileInput" type="file" /></div>
3+
<link rel="stylesheet" type="text/css" href="{{ uploadify_path }}uploadify.css" />
4+
<div id="uploadify" class="multi_file_upload">
5+
<input id="fileInput" name="fileInput" type="file" />
6+
{% if not uploadify_auto %}
7+
<input type="button" value="Upload" id="upload" />
8+
{% endif %}
9+
</div>
410
<script type="text/javascript">// <![CDATA[
511
$(document).ready(function() {
612
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { //test for MSIE x.x;
@@ -10,14 +16,19 @@
1016
}
1117
$('#fileInput').uploadify({
1218
'uploader': '{{ uploadify_path }}uploadify.swf',
13-
'script': '{% url uploadify_upload %}{{ GET_query }}',
19+
'script': '{% url uploadify_upload %}{{ uploadify_query }}',
20+
'scriptData': {{ uploadify_data|safe }},
1421
'cancelImg': '{{ uploadify_path }}cancel.png',
15-
'auto': true,
1622
'removeCompleted': false,
1723
'multi': true,
1824
'onAllComplete': uploadify_allComplete,
1925
'onCancel': uploadify_cancelUpload,
20-
'onComplete': uploadify_complete
26+
'onComplete': uploadify_complete,
27+
{{ uploadify_options|safe }}
28+
});
29+
30+
$('#upload').click(function(){
31+
$('#fileInput').uploadifyUpload();
2132
});
2233
});
2334

@@ -28,6 +39,21 @@
2839
$('#uploadify').trigger('cancelUpload', data);
2940
}
3041
function uploadify_complete(event, ID, fileObj, response, data) {
42+
if (response!='1'){
43+
response = eval('(' +response +')');
44+
45+
var file_div = jQuery("#" + jQuery(event.target).attr('id') + ID);
46+
file_div.addClass('error');
47+
48+
var file_percentage = file_div.find('.percentage');
49+
file_percentage.text(' -');
50+
$(response.{{ uploadify_filename|safe }}).each(function(){
51+
file_percentage.text(file_percentage.text()+" "+this);
52+
});
53+
54+
return false;
55+
}
3156
$('#uploadify').trigger('complete', [ID, fileObj, response, data]);
57+
$('#upload').hide();
3258
}
3359
// ]]></script>
Lines changed: 64 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,76 @@
11
from django import template
22
from uploadify import settings
3+
from django.utils import simplejson
34

45
register = template.Library()
56

67
# -----------------------------------------------------------------------------
78
# multi_file_upload
89
# -----------------------------------------------------------------------------
9-
@register.inclusion_tag('uploadify/multi_file_upload.html', takes_context=True)
10-
def multi_file_upload(context, unique_id=None):
10+
class MultiFileUpload(template.Node):
11+
def __init__(self, sender='uploadify', unique_id=None, options={}, data={}):
12+
self.sender = sender
13+
self.unique_id = unique_id
14+
self.options = {'fileDataName': 'Filedata'}
15+
self.options.update(options)
16+
self.data = {'fileDataName': self.options['fileDataName'],
17+
'sender': str(self.sender)}
18+
self.data.update(data)
19+
20+
def render(self, context):
21+
if self.unique_id is not None:
22+
unique_id = "?unique_id=%s" % str(self.unique_id)
23+
else:
24+
unique_id = ""
25+
26+
js_options = ",".join(map(lambda k: "'%s': '%s'" % (k, self.options[k]),
27+
self.options))
28+
29+
auto = False
30+
if self.options.has_key('auto') and self.options['auto']:
31+
auto = True
32+
33+
context.update({
34+
'uploadify_query': unique_id,
35+
'uploadify_data': simplejson.dumps(self.data),
36+
'uploadify_path': settings.UPLOADIFY_PATH,
37+
'uploadify_options': js_options,
38+
'uploadify_filename': self.options['fileDataName'],
39+
'uploadify_auto': auto,
40+
})
41+
42+
t = template.loader.get_template('uploadify/multi_file_upload.html')
43+
return t.render(context)
44+
45+
46+
@register.tag
47+
def multi_file_upload(parser, token):
1148
"""
1249
Displays a Flash-based interface for uploading multiple files.
1350
For each POST request (after file upload) send GET query with `unique_id`.
51+
52+
{% multi_file_upload sender='SomeThing' fileDataName='Filename' %}
53+
54+
For all options see http://www.uploadify.com/documentation/
55+
1456
"""
15-
if unique_id is not None:
16-
GET_query = '?unique_id=' + str(unique_id)
17-
else:
18-
GET_query = ''
19-
return {
20-
'GET_query' : GET_query,
21-
'uploadify_path' : settings.UPLOADIFY_PATH,
22-
}
57+
args = token.split_contents()
58+
tag_name = args[0]
59+
args = args[1:]
60+
61+
sender = 'uploadify'
62+
unique_id = None
63+
options = {}
64+
65+
for arg in args:
66+
name, val = arg.split("=")
67+
val = val.replace('\'', '').replace('"', '')
68+
if name == 'sender':
69+
sender = val
70+
elif name == 'unique_id':
71+
unique_id = val
72+
else:
73+
options[name] = val
74+
75+
return MultiFileUpload(sender, unique_id, options)
76+

uploadify/views.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,23 @@
11
from django.dispatch import Signal
22
from django.http import HttpResponse
33
from django.views.decorators.csrf import csrf_exempt
4+
from sugar.views.json import JsonResponse
45

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

78
@csrf_exempt
89
def upload(request, *args, **kwargs):
910
if request.method == 'POST':
11+
sender='uploadify'
12+
filename = 'Filename'
13+
if request.POST.has_key('sender'):
14+
sender = request.POST['sender']
15+
if request.POST.has_key('fileDataName'):
16+
filename = request.POST['fileDataName']
1017
if request.FILES:
11-
file_url = upload_received.send(sender='uploadify', request=request,
12-
data=request.FILES['Filedata'])[-1][1]
13-
return HttpResponse(file_url)
18+
receiveds = upload_received.send(sender=sender, request=request,
19+
data=request.FILES[filename])
20+
for received, response in receiveds:
21+
if not response is None:
22+
return JsonResponse(response)
1423
return HttpResponse('1')

uploadify/widgets.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# -*- coding: utf-8 -*-
2+
3+
from uploadify import settings
4+
from django.contrib.admin.widgets import AdminFileWidget
5+
from uploadify.templatetags.uploadify_tags import MultiFileUpload
6+
from django.utils.safestring import mark_safe
7+
from django.template import Context
8+
9+
class UploadifyAdminWidget(AdminFileWidget):
10+
"""
11+
Create uploadify widget. It receive:
12+
'sender' - string (default = uploadify)
13+
'unique_id'
14+
'options' - http://www.uploadify.com/documentation/
15+
'data' - POST data
16+
17+
Example:
18+
self.fields['uploadify'].widget = UploadifyAdminWidget(
19+
attrs={'data': post_data, 'options': {'fileDataName': 'image'}})
20+
"""
21+
22+
js = """
23+
<script type="text/javascript">
24+
$('#uploadify').bind('allUploadsComplete', function(data){
25+
window.location.reload();
26+
});
27+
</script>"""
28+
29+
def __init__(self, *args, **kwargs):
30+
self.sender = 'uploadify'
31+
self.unique_id = None
32+
self.options = {}
33+
self.data = {}
34+
35+
if kwargs.has_key('attrs'):
36+
for attr in kwargs['attrs']:
37+
if attr in ('sender', 'unique_id', 'options', 'data'):
38+
setattr(self, attr, kwargs['attrs'][attr])
39+
super(UploadifyAdminWidget, self).__init__(*args, **kwargs)
40+
41+
def render(self, name, value, attrs=None):
42+
context = Context({})
43+
uploader = MultiFileUpload(self.sender, self.unique_id, self.options, self.data)
44+
template_data = uploader.render(context)
45+
template_data += self.js
46+
47+
return mark_safe(template_data)

0 commit comments

Comments
 (0)