I am writng a Django application that let's you download a file after some requirements have been met (you have to log on, for example). The file needs to be inaccessible otherwise.
Serve the file through Apache won't work: I have to check in the database for the user's permissions. Furthermore, don't have permission to change my Apache configuration.
So I want to read the file in Django, then set the appropriate headers and send it to the client.
I used the information on this page in the Django manual for the headers.
I have the following code:
#<- check persmissons here, continue if allowed ->
#read the pdf file
location = 'file.pdf'
file = open(location, 'r')
content = file.read()
file.close
#serve the file
response = HttpResponse(content, mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=filename.pdf'
return response
However, the downloaded file seems to be corrupt: it can't be opened in A开发者_如何学JAVAdobe Reader. I'm thinking that maybe this is some encoding problem, but I can't figure it out.
Any help is appreciated :)
You have to open()
the file in binary mode (consider docs).
Just like this:
file = open(location, 'rb')
I don't know whether it is applicable to you (since you are not allowed to change your Apache's settings), but I'd suggest to use Lighttpd + mod_secdownload for performance reasons. This elegant solution leverages Lighttpd's optimizations for serving static content while delegating authorization decisions to 3rd party (in your case Django).
精彩评论