tornado上传文件,且把文件进行保存
1.功能
实现文件上传功能(图片),且把上传的文件进行保存
2.实现
2.1项目目录结构

2.2 html页面 upload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/upload/" method="post" enctype="multipart/form-data">
<input type="file" name="images" />
<input type="submit" value="图片上传">
</form>
</body>
</html>
2.3 files.py文件中代码
# -*- coding:utf-8 -*-
#@Time : 2020/9/10 22:55
#@Author: 张君
#@File : files.py
import tornado.web
import tornado.ioloop
import os
class uploadHader(tornado.web.RequestHandler):
def get(self,*args,**kwargs):
self.render('templates/upload.html')
#获取表单内容
def post(self,*args,**kwargs):
#获取表单中的数据,images就是对应的html中name值
image=self.request.files['images']
#得到一系列的数据,获取你想要的内容
for imag in image:
#图片文件名
filename=imag.get('filename')
#图片被转换后的字节内容
body=imag.get('body')
#获取的content_type
content_type=imag.get('content_type')
#获取绝对路径
dir=os.path.join(os.getcwd(),'file',filename)
#写入到文件目录中
with open(dir,'wb') as fw:
fw.write(body)
#显示在屏幕上
self.set_header('Content-Type',content_type)
self.write(body)
#url
app=tornado.web.Application([
(r'/upload/', uploadHader)
])
#绑定端口
app.listen(8888)
print("启动了")
#监控
tornado.ioloop.IOLoop.instance().start()
2.4运行效果

上传图片后,显示图片文件名

点击图片上传.浏览器显示了内容

在来看文件是否已生成

|
作者:做梦的人(小姐姐) 出处:https://www.cnblogs.com/chongyou/ 本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。 如果文中有什么错误,欢迎指出。以免更多的人被误导。 微信号:18582559217 |

浙公网安备 33010602011771号