tornado 文件下载

承接上一篇文章

下载相对简单点,但是遇到文档名为中文时,会异常报错:

“tornado.httputil.HTTPOutputError: Tried to write 557336 bytes less than Content-Length”

    def get(self):
        try:
                    path = self.get_query_arguments("path")[0]
                    filename = (os.path.split(path)[1].encode('utf-8')).decode('ISO-8859-1')
                    #这个很关键,当文档名称带中文时,会报错
                    #tornado.httputil.HTTPOutputError: Tried to write 557336 bytes less than Content-Length

                    self.set_header('Content-Type', 'application/octet-stream')
                    self.set_header('Content-Disposition', 'attachment; filename=' + filename)
                    buf_size = 1024
                    with open(path, 'rb') as f:
                        while True:
                            data = f.read(buf_size)
                            if not data:
                                break
                            self.write(data)
                    self.finish()
        except Exception as e:
            print(e)
           

你可能感兴趣的:(tornado 文件下载)