tornado 文件上傳處理 和 模擬上傳文件

​服務端html

#!/usr/bin/pythonpython

#-*- encoding:utf-8 -*-nginx

import tornado.ioloopweb

import tornado.webapp

import shutiltornado

import osoop

 

class UploadFileHandler(tornado.web.RequestHandler):post

    def get(self):url

        self.write('''code

<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()

 

模擬上傳文件

import requests

 

url = 'http://127.0.0.1:3000/file'

data = {

    'name': 'nginx'

}

files = {'file': open("a.png", 'rb')}

response = requests.post(url, data=data, files=files)

print response.status_code

print response.content

相關文章
相關標籤/搜索