繁体   English   中英

如何使用python中的POST请求在multipart/form-data中发送excel文件?

[英]How to send excel file in multipart/form-data with POST Requests in python?

我试图在多部分/表单数据内容类型的 POST 请求中将一个 excel 文件发送到服务器。 我收到一个错误:

解压的值太多

可能是什么原因? 以下是我正在尝试的请求:

#Data = get_data('C:\foo.xls')
#print Data
Data = open('C:\foo.xls', 'rb')
print Data

headers = {
       'access-control-allow-origin': '*',
       'accept': 'application/json',
       'content-type': 'multipart/form-data', 
       'authorization': 'Basic xxxxxxxxx'
      }   
 R = requests.post('http://testserver:8080/v1/readyapi/executions/'+executionId+'/files', headers=headers, params=params, files=Data)
 print R.content

这是错误:

Traceback (most recent call last):
    (body, content_type) = self._encode_files(files, data)
  File "C:\Python27\lib\site-packages\requests\models.py", line 132, in _encode_files
    for (k, v) in files:
ValueError: too many values to unpack

我自己想不通。 尝试了几件事,没有奏效。 有人可以建议吗?

试试下面的代码

Data = open('C:\foo.xls', 'rb') 
headers = {
       'access-control-allow-origin': '*',
       'accept': 'application/json',
       'content-type': 'multipart/form-data', 
       'authorization': 'Basic xxxxxxxxx'
      }
 files = {"file_name": Data}
 url = 'http://testserver:8080/v1/readyapi/executions/'+executionId+'/files'
 R = requests.post(url, headers=headers, params=params, files=files)
 print R.content

您必须将files参数作为字典传递,或者也可以尝试如下所示

files = {'file': ('foo.xls', open('foo.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}

参考: http : //docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file

试试这个,正确的 MIME 类型很重要( https://wiki.selfhtml.org/wiki/MIME-Type/%C3%9Cbersicht

headers = {
       'access-control-allow-origin': '*',
       'accept': 'application/json',
       'content-type': 'multipart/msexcel', 
       'authorization': 'Basic xxxxxxxxx'
      }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM