首页 > 解决方案 > 使用 python 请求上传文件

问题描述

我在尝试将文件上传到 API 时遇到问题。在 swagger UI 中,手动上传 excel 文件没有问题。当我尝试使用请求上传时,我收到 415 错误(我的文件格式无效)。这是该发布请求的简单代码:

 headers = {
        'Authorization':"bearer "+ CLIENT.token,
        'Content-Type': 'form-data' 
           }
 files = [('file', open(path_to_file, 'rb'))]

 response = requests.post(api_url,  
    files=files,
    headers=headers)

我的回复有状态码 415,我不知道发生了什么。当我使用swagger时,我检查了newtwork浏览器,我在请求中看到了这个header

Content-Type: multipart/form-data; boundary=----WebKitFormBoundarywkrdGd3ROh0GkfsW

但是,我不知道“边界”一词是什么,如果我手动将此标头传递到请求中,API 会抛出 500。

标签: pythonpython-requests

解决方案


服务器说你Content-Type错了。如果您要上传.xls文件,请使用:

'Content-Type': 'application/vnd.ms-excel'

如果您要上传.xlsx文件,请使用:

'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

推荐阅读