tornado中实现文件上传与下载

2018-06-01  本文已影响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()
上一篇下一篇

猜你喜欢

热点阅读