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/p/13653899.html