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運行效果

 

 

上傳圖片后,顯示圖片文件名

 

 點擊圖片上傳.瀏覽器顯示了內容

 

在來看文件是否已生成

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM