从文件下载后,Python会破坏pdf

时间:2014-11-10 23:10:57

标签: python django pdf

当我将文件作为附件下载时,python会以某种方式破坏我的pdf文件。我使用以下代码(并尝试了多种变体)来下载文件:

def print_pdf(request):

    filename = 'real.pdf' 

    response = HttpResponse(file(filename).read())
    response['Content-Type'] = 'application/pdf'
    response['Content-disposition'] = 'attachment'

    return response

原始文件为108KB,结果大约为100bytes。知道我错过了什么/做错了吗?如果我更改了文件名,则表示无法找到该文件,因此似乎python可以访问本地存储的文件。

2 个答案:

答案 0 :(得分:3)

您可能需要以二进制模式打开文件。

pdf = open(filename, 'rb')
response = HttpResponse(pdf.read())

请注意,您不应该依赖这样的媒体文件:这是资产服务器的工作。

答案 1 :(得分:0)

这应该有效:

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