datenaustausch / upload / views.py

from mimetypes import guess_type
import os.path

from django.core.files import File as DjangoFile
from django.http import HttpResponse, Http404, HttpResponseForbidden
from django.shortcuts import render_to_response, get_object_or_404

from datenaustausch.upload.models import File
from datenaustausch.upload.forms import DownloadFileForm

def download(request, download_id):
    f = get_object_or_404(File, pk=download_id)
    if request.method == 'GET':
        form = DownloadFileForm()
        return render_to_response("templates/upload/show_download.html", {"download" : f, 
            'form': form})
    elif request.method == 'POST':
        if not os.path.isfile(f.file_on_fs.name):
            raise Http404("Datei konnte nicht gefunden werden")
        form = DownloadFileForm(request.POST)
        if form.is_valid() and form.cleaned_data['password'] == f.download_password:
            file_to_download = DjangoFile(f.file_on_fs)
            response = HttpResponse(file_to_download, mimetype=guess_type(file_to_download.name)[0])
            response['Content-Disposition'] = 'attachment; filename=%s' % f.filename()
            response['Content-Length'] = os.path.getsize(file_to_download.name)
            return response
        else:
            return HttpResponseForbidden("Zugriff nicht gestattet. Passwort falsch!")
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.