1 from django.utils import simplejson as json
2 from django.core.serializers.json import DjangoJSONEncoder
4 from django.http import HttpResponse, HttpResponseBadRequest, Http404
6 from ajaxuploader.backends.local import LocalUploadBackend
8 class AjaxFileUploader(object):
9 def __init__(self, backend=None, **kwargs):
11 backend = LocalUploadBackend
12 self.get_backend = lambda: backend(**kwargs)
14 def __call__(self,request):
15 print "ajax file uploader called"
16 return self._ajax_upload(request)
18 def _ajax_upload(self, request):
19 if request.method == "POST":
21 # the file is stored raw in the request
24 # AJAX Upload will pass the filename in the querystring if it
25 # is the "advanced" ajax upload
27 filename = request.GET['qqfile']
29 return HttpResponseBadRequest("AJAX request not valid")
30 # not an ajax upload, so it was the "basic" iframe version with
34 if len(request.FILES) == 1:
35 # FILES is a dictionary in Django but Ajax Upload gives
36 # the uploaded file an ID based on a random number, so it
37 # cannot be guessed here in the code. Rather than editing
38 # Ajax Upload to pass the ID in the querystring, observe
39 # that each upload is a separate request, so FILES should
40 # only have one entry. Thus, we can just grab the first
41 # (and only) value in the dict.
42 upload = request.FILES.values()[0]
44 raise Http404("Bad Upload")
45 filename = upload.name
47 backend = self.get_backend()
49 # custom filename handler
50 filename = (backend.update_filename(request, filename)
53 backend.setup(filename)
54 success = backend.upload(upload, filename, is_raw)
56 extra_context = backend.upload_complete(request, filename, upload)
58 # let Ajax Upload know whether we saved it or not
59 ret_json = {'success': success, 'filename': filename}
60 if extra_context is not None:
61 ret_json.update(extra_context)
63 return HttpResponse(json.dumps(ret_json, cls=DjangoJSONEncoder))
65 ajax_uploader = AjaxFileUploader()