tornado 中读取上传的文件
- 1、在postman中向服务器发送文件
- 使用post方法
- 在body中发送文件
- 选择form-data
- 在key中选择file,并定义key名
- 选择需要发送的文件
- 2、读取并保存上传的文件
- 获取文件
- 获取全部文件 files = self.request.files
- 获取指定文件列表 imgs = files.get(‘img’, [])
- 获取文件名 filename = imgs[0].get(‘filename’)
- 获取文件内容 data = imgs[0].get(‘body’)
- 保存文件
- file = open(‘upload/%s’ % filename, ‘wb’)
- file.write(data)
- file.close()
import tornado
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.options import define, options, parse_config_file
from tornado.web import Application, RequestHandler, url
class UploadHandler(RequestHandler):
def get(self):
self.write('upload page')
def post(self, *args, **kwargs):
self.write('upload post page')
files = self.request.files
imgs = files.get('img', [])
for img in imgs:
filename = img.get('filename')
ext = img.get('content_type')
data = img.get('body')
file = open('upload/%s' % filename, 'wb')
file.write(data)
file.close()
define('port', type=int, default=10000, multiple=False)
define('db',multiple=True, type=str, default=[],)
parse_config_file('config')
url_list = [('/upload', UploadHandler)]
app = Application(url_list)
server = HTTPServer(app)
server.listen(options.port)
IOLoop.current().start()
- 3、在form表单中要将enctype设置成为multipart/form-data
<form method=post action=/regrist enctype=multipart/form-data>
<p>用户名:<input type=text name=uname></p>
<p>密码:<input type=password name=upwd></p>
<p>用户头像:<input type=file name=uimg></p>
<p>
<input type=submit value='提交'>
<input type=reset value='重置'>
</p>
</form>