下载为Content-Disposition后的Pdf错误'=附件

问题描述 投票:0回答:1

在我的其余框架中,我在ModelViewSet上有一个检索方法,为

def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        print(serializer.data)
        pdf = serializer.data['pdf']
        response = Response(pdf, content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="invoice.pdf"'
        return response

pdf是FileField类型的模型字段。

我能够自动下载URL上的pdf文件,但是当我尝试打开pdf时出现错误,在chrome上显示“无法加载PDF文档”,在pdf查看器上显示“不支持的文件类型或文件已损坏,(作为电子邮件附件发送且未正确解码)”

我还需要做些什么才能使其正常工作。

虽然pdf格式正确,可以直接打开,

谢谢

django pdf content-type
1个回答
0
投票

因为pdf只是URL,所以无效。

将响应重写为:

response = HttpResponse(instance.pdf, content_type='application/pdf')

已解决问题。

© www.soinside.com 2019 - 2024. All rights reserved.