phicon
phicon

Reputation: 3617

Python corrupts pdf after download from file

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

Answers (2)

Daniel Roseman
Daniel Roseman

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

Tareq
Tareq

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

Related Questions