Python API JSON 上传文件 multipart/form-data 带边界

问题描述

我正在尝试使用 python3 通过 API 上传 *.xlsx 文件,当我发布时,我收到了这个:

{
  "timestamp" : "2021-01-08T07:47:44.462+0000","status" : 400,"error" : "Bad Request","exception" : "org.springframework.web.multipart.support.MissingServletRequestPartException","message" : "required request part 'file' is not present","path" : "/importFile/"
}

部分代码

    base_url_import = "URL/importFile/"
    headers_import = {'accept':'*/*','Cookie':downloaded_cookies,'Content-Type':'multipart/form-data; boundary=------WebKitFormBoundaryTChBFmdsvOIemd9N--'}
    payload_import = {'Content-disposition':'form-data; name=file; filename=file_to_upload','Content-Type':'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}

    response_import = ses.post(base_url_import,data=json.dumps(payload_import),headers=headers_import)

我尝试更改部分 filename=file_to_upload 到文件的特定路径 但效果是一样的

当我将 json.dumps 更改为 json.loads 时:

Traceback (most recent call last):
  File "./api_import_file.py",line 47,in <module>
    main()
  File "./api_import_file.py",line 42,in main
    response_import = ses.post(base_url_import,data=json.loads(payload_import),headers=headers_import)
  File "/usr/lib/python3.8/json/__init__.py",line 341,in loads
    raise TypeError(f'the JSON object must be str,bytes or bytearray,'
TypeError: the JSON object must be str,not dict

解决方法

尝试使用 json 更改数据关键字,例如

response_import = ses.post(base_url_import,json=json.dumps(payload_import),headers=headers_import)