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

相关文章
相关标签/搜索