Max.Bai
2017-08
>>> url = 'http://httpbin.org/post'
>>> files = {'file': open('report.xls', 'rb')}
>>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": ""
},
...
}
你可以显式地设置文件名,文件类型和请求头:
>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
>>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": ""
},
...
}
如果你想,你也可以发送作为文件来接收的字符串:
>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}
>>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": "some,data,to,send\\nanother,row,to,send\\n"
},
...
}
只要把文件设到一个元组的列表中,其中元组结构为 (form_field_name, file_info)
按照如下格式发送数据
data = {'ts_id': tsid}
files = [('images',('1.png', open('/home/1.png', 'rb'),'image/png')),('images',('2.png', open('/home/2.png', 'rb'),'image/png'))]
r = requests.post(url, data=data, files=files)
print r.text
from werkzeug.utils import secure_filename
def upload_file(request):
if request.method == 'POST':
uploaded_files = request.FILES.getlist("images")
try:
for file in uploaded_files:
filename = secure_filename(file.name)
handle_uploaded_file(os.path.join(ft, filename), file)
except Exception as e:
result_json = {"msg": str(e)}
result = {
'json': result_json
}
return JsonResponse(result, safe=False)
def handle_uploaded_file(filename, f):
try:
destination = open(filename, 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
except Exception as e:
raise Exception('save %s failed: %s' % (filename, str(e)))
requests 官网:http://docs.python-requests.org/zh_CN/latest/user/quickstart.html#post-multipart-encoded