Python从文件下载后会损坏pdf



当我以附件的形式下载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,结果约为100字节。知道我错过了什么/做错了什么吗?如果我更改文件名是说它找不到文件,所以看起来python可以访问本地存储的文件。

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

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

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

这应该有效:

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

最新更新