關於tornado檔案上傳與儲存
阿新 • • 發佈:2019-01-28
#!/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') #檔案的暫存路徑(在py檔案同目錄下創一個files資料夾來儲存) file_metas=self.request.files['file'] #提取表單中‘name’為‘file’的檔案元資料(一個檔案元包括:[{'body':' XXX', 'content_type':'XXXX', 'filename':'XXXX'}]) for meta in file_metas: filename=meta['filename'] filepath=os.path.join(upload_path,filename) with open(filepath,'wb') as up: #有些檔案需要已二進位制的形式儲存,實際中可以更改(注意學習with ... as 關鍵詞的用法) 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()