Source

datenaustausch / upload / views.py

Full commit
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!")