python - 使用 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。
解决方案
服务器说你Content-Type
错了。如果您要上传.xls
文件,请使用:
'Content-Type': 'application/vnd.ms-excel'
如果您要上传.xlsx
文件,请使用:
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
推荐阅读
- java - 来自 Firebase 的数据未显示在 RecyclerView 中
- php - 如果表单验证失败,则使用自定义请求类(laravel 5.8)通过输入重定向回来
- python - Flask 会话数据可以被用户(威胁参与者)更改吗?
- android - Android Studio 中的 Gradle 依赖项
- three.js - 我可以将 THREE.js 材料放在 gltf 模型上吗?
- git - 如何在 Mac 上为 Fork 配置 SSH 私钥?
- c++ - 合并排序和合并 C++
- php - Laravel 5.8 无法解析的依赖解析 [参数#0 [
$message ]] 在类异常中 - node.js - 无法从 MongoDB 检索文档
- java - 当我为多个构造函数注入参数时为什么会模棱两可?