代码:html
Flask file uploadpython
$ curl -F 'file=@"foo.png";filename="bar.png"' 127.0.0.1:5000
注意:使用上传文件功能的时候使用 POST form-data,参数名就是参数名(通常会提早约定好,而不是变化的文件名),参数的值是一个文件(这个文件正常是有文件名的)。git
有时候脚本生成了要上传的文件,但并无留在本地的需求,因此使用临时文件的方式,生成成功了就直接上传。github
tempfile 会在系统的临时目录中建立文件,使用完了以后会自动删除。flask
import requests import tempfile url = 'http://127.0.0.1:5000' temp = tempfile.NamedTemporaryFile(mode='w+', suffix='.txt') try: temp.write('Hello Temp!') temp.seek(0) files = {'file': temp} r = requests.post(url, files=files, proxies=proxies) finally: # Automatically cleans up the file temp.close()
或者直接使用 StringIO,能够直接在内存中完成整个过程。app
import requests from StringIO import StringIO url = 'http://127.0.0.1:5000' temp = StringIO() temp.write('Hello Temp!') temp.seek(0) temp.name = 'hello-temp.txt' # StringIO 的实例没有文件名,须要本身手动设置,不设置 POST 过去那边的文件名会是 'file' files = {'file': temp} r = requests.post(url, files=files)
补上发现的一段能够上传多个同名附件的代码:curl
files = [ ("attachments", (display_filename_1, open(filename1, 'rb'),'application/octet-stream')), ("attachments", (display_filename_2, open(filename2, 'rb'),'application/octet-stream')) ] r = requests.post(url, files=files, data=params)