【问题标题】:Pdf error after download as Content-Disposition' = attachment下载为 Content-Disposition' = 附件后的 Pdf 错误
【发布时间】:2020-04-28 07:16:04
【问题描述】:

在我的休息框架中,我在 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】:

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

    将响应重写为:

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

    解决了这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-19
      • 1970-01-01
      • 2016-12-18
      • 1970-01-01
      • 2013-12-06
      • 2023-03-08
      • 1970-01-01
      相关资源
      最近更新 更多