Permalink
Browse files

Improved uploader and demo project

  • Loading branch information...
1 parent 232d3e2 commit 245c0d4269d48c2e909e9cabb3f010cc76a036c2 @samluescher committed Jun 3, 2012
Binary file not shown.
@@ -1,7 +1,7 @@
<!doctype html>
<html lang="en"><head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
- <meta name="robots" content="NONE,NOARCHIVE"><title>Welcome to Django</title>
+ <meta name="robots" content="NONE,NOARCHIVE"><title>Welcome to Django Media Tree</title>
<style type="text/css">
html * { padding:0; margin:0; }
body * { padding:10px 20px; }
@@ -60,13 +60,6 @@
from django.utils.text import capfirst
import os
-try:
- # Django 1.2
- from django.views.decorators.csrf import csrf_view_exempt
-except ImportError:
- # pre 1.2
- from django.contrib.csrf.middleware import csrf_view_exempt
-
STATIC_SUBDIR = app_settings.MEDIA_TREE_STATIC_SUBDIR
@@ -120,18 +113,12 @@ class FileNodeAdmin(MPTTModelAdmin):
class Media:
js = [
- os.path.join(STATIC_SUBDIR, 'lib/swfupload/swfupload_fp10', 'swfupload.js'),
- os.path.join(STATIC_SUBDIR, 'lib/swfupload/plugins', 'swfupload.queue.js'),
- os.path.join(STATIC_SUBDIR, 'lib/swfupload/plugins', 'swfupload.cookies.js'),
os.path.join(STATIC_SUBDIR, 'lib/jquery', 'jquery-1.7.1.min.js'),
os.path.join(STATIC_SUBDIR, 'lib/jquery', 'jquery.ui.js'),
os.path.join(STATIC_SUBDIR, 'lib/jquery', 'jquery.cookie.js'),
+ os.path.join(STATIC_SUBDIR, 'lib', 'fileuploader.js'),
os.path.join(STATIC_SUBDIR, 'js', 'admin_enhancements.js'),
os.path.join(STATIC_SUBDIR, 'js', 'django_admin_fileuploader.js'),
-
- os.path.join(STATIC_SUBDIR, 'js', 'jquery.swfupload_manager.js'),
-
- os.path.join(STATIC_SUBDIR, 'lib', 'fileuploader.js'),
]
css = {
'all': (
@@ -331,7 +318,8 @@ def size_formatted(self, node, with_descendants=True):
size_formatted.allow_tags = True
def init_parent_folder(self, request):
- folder_id = request.GET.get('folder_id', None) or request.POST.get('parent', None)
+ folder_id = request.GET.get('folder_id', None) or \
+ request.GET.get('parent') or request.POST.get('parent', None)
reduce_levels = request.GET.get('reduce_levels', None) or request.POST.get('reduce_levels', None)
if folder_id or reduce_levels:
request.GET = request.GET.copy()
@@ -522,60 +510,62 @@ def get_form(self, request, *args, **kwargs):
# Upload view is exempted from CSRF protection since SWFUpload cannot send cookies (i.e. it can only
# send cookie values as POST values, but that would render this check useless anyway).
# However, Flash Player should already be enforcing a same-domain policy.
- @csrf_view_exempt
+ @csrf_protect_m
+ @transaction.commit_on_success
def upload_file_view(self, request):
+ try:
+ if not self.has_add_permission(request):
+ raise PermissionDenied
- if not self.has_add_permission(request):
- raise PermissionDenied
-
- FILE_PARAM_NAME = 'qqfile'
-
- self.init_parent_folder(request)
-
- if request.method == 'POST':
+ FILE_PARAM_NAME = 'qqfile'
+ self.init_parent_folder(request)
- if request.is_ajax() and request.GET.get(FILE_PARAM_NAME, None):
- from django.core.files.base import ContentFile
- from django.core.files.uploadedfile import UploadedFile
- content_file = ContentFile(request.raw_post_data)
- uploaded_file = UploadedFile(content_file, request.GET.get(FILE_PARAM_NAME), None, content_file.size)
+ if request.method == 'POST':
- form = UploadForm(request.POST, {'file': uploaded_file})
-
-
- else:
- form = UploadForm(request.POST, request.FILES)
-
-
- if form.is_valid():
- node = FileNode(file=form.cleaned_data['file'], node_type=FileNode.FILE)
- parent_folder = self.get_parent_folder(request)
- if not parent_folder.is_top_node():
- node.parent = parent_folder
- self.save_model(request, node, None, False)
- # Respond with 'ok' for the client to verify that the upload was successful, since sometimes a failed
- # request would not result in a HTTP error and look like a successful upload.
- # For instance: When requesting the admin view without authentication, there is a redirect to the
- # login form, which to SWFUpload looks like a successful upload request.
- if request.is_ajax():
- return HttpResponse('{"success": true}', mimetype="application/json")
+ if request.is_ajax() and request.GET.get(FILE_PARAM_NAME, None):
+ from django.core.files.base import ContentFile
+ from django.core.files.uploadedfile import UploadedFile
+ content_file = ContentFile(request.raw_post_data)
+ uploaded_file = UploadedFile(content_file, request.GET.get(FILE_PARAM_NAME), None, content_file.size)
+ form = UploadForm(request.POST, {'file': uploaded_file})
+ else:
+ form = UploadForm(request.POST, request.FILES)
+
+ if form.is_valid():
+ node = FileNode(file=form.cleaned_data['file'], node_type=FileNode.FILE)
+ parent_folder = self.get_parent_folder(request)
+ if not parent_folder.is_top_node():
+ node.parent = parent_folder
+ self.save_model(request, node, None, False)
+ # Respond with 'ok' for the client to verify that the upload was successful, since sometimes a failed
+ # request would not result in a HTTP error and look like a successful upload.
+ # For instance: When requesting the admin view without authentication, there is a redirect to the
+ # login form, which to SWFUpload looks like a successful upload request.
+ if request.is_ajax():
+ return HttpResponse('{"success": true}', mimetype="application/json")
+ else:
+ messages.info(request, _('Successfully uploaded file %s.') % node.name)
+ return HttpResponseRedirect(reverse('admin:media_tree_filenode_changelist'))
else:
- messages.info(request, _('Successfully uploaded file %s.') % node.name)
- return HttpResponseRedirect(reverse('admin:media_tree_filenode_changelist'))
+ # invalid form data
+ if request.is_ajax():
+ return HttpResponse('{"error": "%s"}' % ' '.join(
+ [item for sublist in form.errors.values() for item in sublist]),
+ mimetype="application/json")
+
+ # Form is rendered for troubleshooting SWFUpload. If this form works, the problem is not server-side.
+ if not settings.DEBUG:
+ raise ViewDoesNotExist
+ if request.method == 'GET':
+ form = UploadForm()
+ return render_to_response('admin/media_tree/filenode/upload_form.html', {'form': form})
+
+ except Exception as e:
+ if request.is_ajax():
+ return HttpResponse('{"error": "%s"}' % ugettext('Server Error'),
+ mimetype="application/json")
else:
- # invalid form data
-
- if request.is_ajax():
- return HttpResponse('{"error": "%s"}' % ' '.join(
- [item for sublist in form.errors.values() for item in sublist]),
- mimetype="application/json")
-
- # Form is rendered for troubleshooting SWFUpload. If this form works, the problem is not server-side.
- if not settings.DEBUG:
- raise ViewDoesNotExist
- if request.method == 'GET':
- form = UploadForm()
- return render_to_response('admin/media_tree/filenode/upload_form.html', {'form': form})
+ raise
def open_path_view(self, request, path=''):
if path is None or path == '':
@@ -1,8 +1,7 @@
jQuery(function($) {
- DjangoAdminFileUploader = function(o){
+ DjangoAdminFileUploader = function(o) {
// call parent constructor
qq.FileUploader.apply(this, arguments);
-
// this method is completely replaced by showing messages in queue
// and/or errorlist
this._options.showMessage = function(message) { };
@@ -12,7 +11,9 @@ jQuery(function($) {
upload_errors: 0,
successful_uploads: 0
}
- }
+
+ this._handler._options.csrfmiddlewaretoken = this._options.csrfmiddlewaretoken;
+ };
qq.extend(DjangoAdminFileUploader.prototype, qq.FileUploader.prototype);
@@ -192,7 +193,49 @@ jQuery(function($) {
self._setQueueMessage();
}
});
- }
+ }
+ });
+ qq.extend(qq.UploadHandlerXhr.prototype, {
+ /*
+ The only reason why we're overriding this method is that we need to
+ set the X-CSRFToken header (second to last line).
+ */
+ _upload: function(id, params) {
+ var file = this._files[id],
+ name = this.getName(id),
+ size = this.getSize(id);
+
+ this._loaded[id] = 0;
+
+ var xhr = this._xhrs[id] = new XMLHttpRequest();
+ var self = this;
+
+ xhr.upload.onprogress = function(e){
+ if (e.lengthComputable){
+ self._loaded[id] = e.loaded;
+ self._options.onProgress(id, name, e.loaded, e.total);
+ }
+ };
+
+ xhr.onreadystatechange = function(){
+ if (xhr.readyState == 4){
+ self._onComplete(id, xhr);
+ }
+ };
+
+ // build query string
+ params = params || {};
+ params['qqfile'] = name;
+ var queryString = qq.obj2url(params, this._options.action);
+
+ xhr.open("POST", queryString, true);
+ xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
+ xhr.setRequestHeader("X-File-Name", encodeURIComponent(name));
+ xhr.setRequestHeader("Content-Type", "application/octet-stream");
+ xhr.setRequestHeader("X-CSRFToken", this._options.csrfmiddlewaretoken);
+ xhr.send(file);
+ }
});
+
});
@@ -27,20 +27,11 @@
<span class="caption">Uploader: {% trans "Upload files" %}</span></span>
</a>
</li>
- {% if swfupload_upload_url %}
- <li class="swfupload-button-container">
- <a href="javascript:void(0)" class="addlink swfupload">
- <span class="caption">{% trans "Upload files" %}</span>
- <span class="swfupload-button-overlay"><span id="swfupload-button"></span></span>
- </a>
- </li>
- {% else %}
- <li>
- <a href="{% url admin:media_tree_filenode_add %}?parent=&{% if is_popup %}_popup=1{% endif %}" class="addlink">
- {% trans "Add file" %}
- </a>
- </li>
- {% endif %}
+ <li>
+ <a href="{% url admin:media_tree_filenode_add %}?parent=&{% if is_popup %}_popup=1{% endif %}" class="addlink">
+ {% trans "Add file" %}
+ </a>
+ </li>
<li>
<a id="object-tool-add-folder" href="{% url admin:media_tree_filenode_add_folder %}{% if is_popup %}?_popup=1{% endif %}" class="addlink folder">
<span class="caption">{% trans "Add folder" %}</span>
@@ -51,19 +42,7 @@
<script type="text/javascript">// <![CDATA[
jQuery(function($) {
- var uploader = new DjangoAdminFileUploader({
- element: $('.changelist-file-uploader')[0],
- action: '{% url admin:media_tree_filenode_upload %}',
- debug: true,
- listElement: $('#changelist tbody')[0]
- });
-
- });
- // ]]></script>
-
-
- <script type="text/javascript">// <![CDATA[
- jQuery(function($) {
+ /*
{% if swfupload_upload_url %}
var uploadManager = $.SWFUploadManager({
upload_url: '{{ swfupload_upload_url }}'
@@ -76,12 +55,21 @@
,button_height: "30"
});
{% endif %}
+ */
var initialFolder, targetFolder;
{% if node and not node.is_top_node %}
initialFolder = {name: '{{ node.name }}', id: '{{ node.pk }}'};
{% endif %}
+ var uploader = new DjangoAdminFileUploader({
+ element: $('.changelist-file-uploader')[0],
+ action: '{% url admin:media_tree_filenode_upload %}',
+ debug: true,
+ listElement: $('#changelist tbody')[0],
+ csrfmiddlewaretoken: '{{ csrf_token }}'
+ });
+
var setTargetFolder = function(targetFolder) {
$('#changelist').data('targetFolder', targetFolder);
var targetId = '';
@@ -94,11 +82,18 @@
} else {
$('.target-folder').html('');
}
+
var addlink = $('.addlink')[0];
- addlink.href = addlink.href.replace(/parent=[0-9]*/, 'parent='+targetId);
+ addlink.href = addlink.href.replace(/parent=[0-9]*/, 'parent='+targetId);
+ uploaderParams = {parent: targetId};
+ uploader.setParams(uploaderParams);
+
+
+ /*
{% if swfupload_upload_url %}
uploadManager.targetFolder = targetFolder;
{% endif %}
+ */
};
setTargetFolder(initialFolder);

0 comments on commit 245c0d4

Please sign in to comment.