7

I am new to Tornado framework. When I set the header type application/pdf, But it takes only default MIME Type i.e; plian/text. Here my code,

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())

It is downloading successfully through web browser. Here url http:/203.193.173.102:8888/. But when I open the pdf file it is not opened. Any one help me. Thanks

2
  • Why do you open requirement.txt instead of test.pdf?
    – falsetru
    Aug 21, 2013 at 10:02
  • Thanks for reply. I don't know how to read pdf file in tornado.
    – dhana
    Aug 21, 2013 at 10:04

1 Answer 1

9

Give it a try:

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())
3
  • I am tried this. But it gives the error --> UnicodeDecodeError: 'utf8' codec can't decode byte 0xb5 in position 10: invalid start byte
    – dhana
    Aug 21, 2013 at 11:12
  • @dhana could you try to replace open('test.pdf', 'r') with codecs.open('test.pdf', 'r', 'utf-8')? (also, don't forget to import codecs).
    – alecxe
    Aug 21, 2013 at 12:14
  • Thanks for reply. I have tried as you said. But it gives the --> UnicodeDecodeError: 'utf8' codec can't decode byte 0xb5 in position 10: invalid start byte. Please solve my problem.
    – dhana
    Aug 21, 2013 at 12:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.