Reputation: 3617
Somehow python corrupts my pdf file when i download the file as an attachment. I use the following code (and tried multiple variations) to download the file:
def print_pdf(request):
filename = 'real.pdf'
response = HttpResponse(file(filename).read())
response['Content-Type'] = 'application/pdf'
response['Content-disposition'] = 'attachment'
return response
The original file is 108KB, the result is about 100bytes. Any idea what i am missing / doing wrong? If i change the filename is says it can not find the file, so it seems python has access to the local stored file.
Upvotes: 1
Views: 1375
Reputation: 600059
You probably need to open your file in binary mode.
pdf = open(filename, 'rb')
response = HttpResponse(pdf.read())
Note though that you shouldn't rely be serving media files like this: that's the job of your asset server.
Upvotes: 4
Reputation: 788
This should work:
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename="{filename}"'.format(filename=filename)
response['Content-Type'] = 'application/pdf'
response.write(open(filename).read())
return response
Upvotes: 0