1. 文件目录
2. HTML页面
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
{#
action 与服务器交互
method 提交方式
enctype 文件传输必备参数
name 后台获取HTML参数
#}
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" multiple="multiple" name="picture">
<input type="submit">
</form>
</body>
</html>
3. web 服务
import time
import tornado.web
import tornado.options
from tornado.options import define, options
from tornado.web import RequestHandler
import tornado.httpserver
import tornado.ioloop
define('port', default=8080, help='run port', type=int)
class UploadHandler(RequestHandler):
"""
get方法:渲染页面
post方法:前后端数据交互
"""
def get(self):
self.render('upload.html')
def post(self):
# picture html 页面name属性
img_list = self.request.files.get('picture')
for img in img_list:
# 图片名
filename = img['filename']
# 二进制数据
content = img['body']
# 保存路径
path = './static/images/{}'.format(filename)
with open(path, 'wb') as f:
f.write(content)
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r'/upload', UploadHandler)
]
settings = dict(
debug=True,
template_path='template',
static_path='static'
)
super(Application, self).__init__(handlers, **settings)
app = Application()
if __name__ == '__main__':
tornado.options.parse_command_line()
print('监听端口: ', options.port)
server = tornado.httpserver.HTTPServer(app)
server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
4. 上传图片;选择图片然后提交