【问题标题】:How to serve a pdf as a download programmatically in GAE and Webapp2?如何在 GAE 和 Webapp2 中以编程方式提供 pdf 作为下载?
【发布时间】:2015-02-13 12:41:46
【问题描述】:

我是使用 GAE 的新手,我束手无策。

我有一个网页显示一个表单,提交时(使用 angularjs $http)应该会导致用户被提供 pdf 下载。 pdf 位于我使用 appcfg 上传到 GAE 的文件夹的根目录中,目前可以通过浏览到 mydomain/mypdf.pdf 来查看。

我处理返回 pdf 的代码在这里:

import os
import webapp2

class ServePDF(webapp2.RequestHandler):
    def post(self):
        q = 'mypdf.pdf'
        self.response.headers['Content-Type'] = 'application/octet-stream'
        self.response.headers['Content-Disposition'] = 'attachment; filename="%s"' % q
        self.response.out.write (open(os.path.dirname(__file__) + '/' + q).read())

app = webapp2.WSGIApplication([
    ('/servepdf', ServePDF)
], debug=True)

我的 app.yaml 看起来像这样:

application: myapp
version: 1
runtime: python27
api_version: 1
threadsafe: true

handlers:
- url: /(.*\.(gif|png|jpg|ico|js|css))
  static_files: \1
  upload: (.*\.(gif|png|jpg|ico|js|css))

- url: /mypdf.pdf
  static_files: mypdf.pdf
  upload: mypdf.pdf 

- url: /robots.txt
  static_files: robots.txt
  upload: robots.txt 

- url: .*
  script: main.app

libraries:
- name: webapp2
  version: latest

我看到的是,由于 500(内部服务器错误),pdf 从未出现过,Google 开发者控制台给了我这个响应:

  File "/base/data/home/apps/myapp/1.382205997234590276/main.py", line 9, in post
    self.response.out.write (open(os.path.dirname(__file__) + '/' + q).read())
IOError: [Errno 2] No such file or directory: '/base/data/home/apps/myapp/1.382205997234590276/mypdf.pdf'

也许我的 app.yaml 有问题?感谢您的帮助。

【问题讨论】:

    标签: google-app-engine pdf webapp2


    【解决方案1】:

    您的 mypdf.pdf 未设置为应用程序可读。你可以在 app.yaml 中做到这一点

    - url: /mypdf.pdf
      static_files: mypdf.pdf
      upload: mypdf.pdf 
      application_readable: true
    

    【讨论】:

    • 谢谢。这使错误消失了。 pdf 还没有出现,但我认为我需要以某种方式在 angularjs 中处理它(这可能会变成一个新问题......)。
    猜你喜欢
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 2011-03-26
    • 2015-09-22
    • 2019-09-07
    • 1970-01-01
    相关资源
    最近更新 更多