如何在tornado中处理MIME类型?

7

我是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 - falsetru
谢谢回复。我不知道如何在Tornado中读取PDF文件。 - dhana
1个回答

9

试一试:

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'编解码器无法解码第10个字节0xb5:起始字节无效。 - dhana
@dhana 你能试着将 open('test.pdf', 'r') 替换为 codecs.open('test.pdf', 'r', 'utf-8') 吗?(同时,别忘了 import codecs)。 - alecxe
谢谢回复。我已按照您所说的尝试了。但是它会出现--> UnicodeDecodeError: 'utf8'编解码器无法解码第10个位置的0xb5字节:无效的起始字节。请帮我解决这个问题。 - dhana

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接