3 from .forms import UploadForm
4 from django.views.generic import FormView, View
5 from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden, Http404
6 from django.conf import settings
9 class JSONResponse(HttpResponse):
10 """JSON response class."""
11 def __init__(self, obj='', mimetype="application/json", *args, **kwargs):
12 content = json.dumps(obj)
13 super(JSONResponse, self).__init__(content, mimetype, *args, **kwargs)
15 class UploadView(FormView):
16 template_name = "fileupload/picture_form.html"
17 form_class = UploadForm
19 def get_safe_path(self, filename=""):
20 path = os.path.abspath(os.path.join(
24 if not path.startswith(settings.MEDIA_ROOT):
27 if not path.startswith(self.get_safe_path()):
31 def get_url(self, filename=""):
32 return settings.MEDIA_URL + self.get_directory() + filename
34 def dispatch(self, request, *args, **kwargs):
35 self.object = self.get_object(request, *args, **kwargs)
36 return super(UploadView, self).dispatch(request, *args, **kwargs)
38 def get(self, request, *args, **kwargs):
42 path = self.get_safe_path()
43 if os.path.isdir(path):
44 for f in os.listdir(path):
47 "url": self.get_url(f),
48 'thumbnail_url': self.get_url(f), # FIXME: thumb!
49 'delete_url': "%s?file=%s" % (request.get_full_path(), f), # FIXME: encode
50 'delete_type': "DELETE"
52 return JSONResponse(files)
54 return super(UploadView, self).get(request, *args, **kwargs)
56 def form_valid(self, form):
57 f = self.request.FILES.get('file')
58 path = self.get_safe_path()
60 if not os.path.isdir(path):
62 with open(self.get_safe_path(f.name), 'w') as destination:
63 for chunk in f.chunks():
64 destination.write(chunk)
67 'url': self.get_url(f.name),
68 'thumbnail_url': self.get_url(f.name), # FIXME: thumb!
69 'delete_url': "%s?file=%s" % (self.request.get_full_path(), f.name), # FIXME: encode
70 'delete_type': "DELETE"
72 response = JSONResponse(data)
73 response['Content-Disposition'] = 'inline; filename=files.json'
76 def delete(self, request, *args, **kwargs):
77 os.unlink(self.get_safe_path(request.GET.get('file')))
78 response = JSONResponse(True)
79 response['Content-Disposition'] = 'inline; filename=files.json'