【问题标题】:How to handle MIME type in tornado?如何处理龙卷风中的 MIME 类型?
【发布时间】:2013-08-21 10:00:12
【问题描述】:

我是 Tornado 框架的新手。当我设置标题类型application/pdf时,但它只需要默认的MIME类型,即; plian/text。这是我的代码,

class MainHandler(tornado.web.RequestHandler):
    def get(self):
            ifile = open("requirements.txt", "r")
            self.set_header('Content-Type', 'application/pdf; charset="utf-8"')
            self.set_header('Content-Disposition', 'attachment; filename="test.pdf"')
            #print(self.list_headers())
            self.write(ifile.read())

通过网络浏览器下载成功。这里网址 http://203.193.173.102:8888/。 但是当我打开pdf文件时它没有打开。任何人帮助我。谢谢

【问题讨论】:

  • 你为什么打开requirement.txt而不是test.pdf
  • 感谢您的回复。我不知道如何在龙卷风中阅读 pdf 文件。

标签: python tornado


【解决方案1】:

试一试:

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        with open('test.pdf', 'rb') as f:  
            self.set_header("Content-Type", 'application/pdf; charset="utf-8"')
            self.set_header("Content-Disposition", "attachment; filename=test.pdf")                  
            self.write(f.read())

【讨论】:

  • 我试过这个。但它给出了错误--> UnicodeDecodeError: 'utf8' codec can't decode byte 0xb5 in position 10: invalid start byte
  • @dhana 你能尝试用codecs.open('test.pdf', 'r', 'utf-8') 替换open('test.pdf', 'r') 吗? (另外,别忘了import codecs)。
  • 感谢您的回复。你说的我已经试过了。但它给出了 --> UnicodeDecodeError: 'utf8' codec can't decode byte 0xb5 in position 10: invalid start byte。请解决我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多