1. 程式人生 > >Tornado web開發之簡單檔案上傳

Tornado web開發之簡單檔案上傳

1、介紹

我們知道,在web開發過程中,檔案上傳是經常用到的功能,比如上傳附件,上傳照片等

下面我們來介紹一下利用tornado 來實現檔案上傳功能

2.程式碼

由於實現檔案上傳的表單很簡單,只需要幾行html,我們把他們直接嵌入到python程式碼中

廢話少說,直接上程式碼:

#!/usr/bin/python
#-*- encoding:utf-8 -*-
import tornado.ioloop
import tornado.web
import shutil
import os

class UploadFileHandler(tornado.web.RequestHandler):
    def get(self):
        self.write('''
<html>
  <head><title>Upload File</title></head>
  <body>
    <form action='file' enctype="multipart/form-data" method='post'>
    <input type='file' name='file'/><br/>
    <input type='submit' value='submit'/>
    </form>
  </body>
</html>
''')

    def post(self):
        upload_path=os.path.join(os.path.dirname(__file__),'files')  #檔案的暫存路徑
        file_metas=self.request.files['file']    #提取表單中‘name’為‘file’的檔案元資料
        for meta in file_metas:
            filename=meta['filename']
            filepath=os.path.join(upload_path,filename)
            with open(filepath,'wb') as up:      #有些檔案需要已二進位制的形式儲存,實際中可以更改
                up.write(meta['body'])
            self.write('finished!')

app=tornado.web.Application([
    (r'/file',UploadFileHandler),
])

if __name__ == '__main__':
    app.listen(3000)
    tornado.ioloop.IOLoop.instance().start()


加入shutil當初是為了把暫存在本地的檔案移到其他目錄中,本程式碼中未實現