用户在Google App Engine中下载的pdf文件返回损坏的pdf文件

2024-03-28 16:12:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经创建了一个python脚本,它使用reportlab从提供的用户数据生成PDF。当我从命令行运行脚本时,pdf下载良好,一切正常。但是,当我尝试将文件传递给Google App Engine时:

...

outputstream = StringIO.StringIO()
PDF = output.write(outputstream)

class PDFHandler(webapp2.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'application/pdf'
        self.response.headers['Content-Disposition'] = 'attachment; filename=Myfile.pdf'
        self.response.headers['Content-Transfer-Encoding'] = 'binary'
        self.response.out.write(PDF)

运行开发服务器,下载PDF文件,但当我试图打开它时,chrome说它不能打开文件,Ubuntu的文档查看器说“无法打开纯文本文档”,即使我检查文档属性时,它显示的是“application/PDF”,并且有相应的.PDF后缀,当我试图在GIMP image viewer中打开它时,它声明“文档已损坏”。我将文件传递给webapp2处理程序的方式有问题吗?任何帮助将不胜感激!在


Tags: 文件文档self脚本pdfapplicationresponsecontent
1条回答
网友
1楼 · 发布于 2024-03-28 16:12:47

我复习了一些旧的教程,解决了这个问题。在最后一行代码中,我忽略了在输出中包含.getvalue():

outputstream = StringIO.StringIO()
PDF = output.write(outputstream)

class PDFHandler(webapp2.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'application/pdf'
        self.response.headers['Content-Disposition'] = 'attachment; filename=Myfile.pdf'
        self.response.headers['Content-Transfer-Encoding'] = 'binary'
        self.response.out.write(PDF.getvalue())

相关问题 更多 >