美文网首页
tornado中实现文件上传与下载

tornado中实现文件上传与下载

作者: 马小跳_ | 来源:发表于2018-06-01 17:52 被阅读69次

    上传

    #!/usr/bin/env python
    # -*- coding: UTF-8 -*-
    
    import tornado.ioloop
    import tornado.web
    import os
    
    class UploadFileHandler(tornado.web.RequestHandler):
        def get(self):
            self.write('''
            <html>
              <head><title>Upload File</title></head>
              <body>
                <form action='file' enctype="multipart/form-data" method='post'>
                <input type='file' name='file'/><br/>
                <input type='submit' value='submit'/>
                </form>
              </body>
            </html>
            ''')
    
        def post(self):
            #文件的暂存路径
            upload_path=os.path.join(os.path.dirname(__file__),'files')  
            #提取表单中‘name’为‘file’的文件元数据
            file_metas=self.request.files['file']    
            for meta in file_metas:
                filename=meta['filename']
                filepath=os.path.join(upload_path,filename)
                #有些文件需要已二进制的形式存储,实际中可以更改
                with open(filepath,'wb') as up:      
                    up.write(meta['body'])
                self.write('finished!')
    
    app=tornado.web.Application([
        (r'/file',UploadFileHandler),
    ])
    
    if __name__ == '__main__':
        app.listen(3000)
        tornado.ioloop.IOLoop.instance().start()
    

    下载

    def post(self,filename):
        print('i download file handler : ',filename)
        #Content-Type这里我写的时候是固定的了,也可以根据实际情况传值进来
        self.set_header ('Content-Type', 'application/octet-stream')
        self.set_header ('Content-Disposition', 'attachment; filename='+filename)
        #读取的模式需要根据实际情况进行修改
        with open(filename, 'rb') as f:
            while True:
                data = f.read(buf_size)
                if not data:
                    break
                self.write(data)
        #记得要finish
        self.finish()
    

    相关文章

      网友评论

          本文标题:tornado中实现文件上传与下载

          本文链接:https://www.haomeiwen.com/subject/nimksftx.html