使用Microsoft Graph REST API向SharePoint上传二进制文件的请求体格式及错误排查
问题核心
你遇到的错误根源是请求头与请求体格式不匹配:你设置了Content-Type: application/json,但实际发送的是二进制文件内容,Graph API会尝试将二进制数据解析为JSON,自然导致解析失败。
正确配置方案
1. 选择正确的API端点
上传二进制文件到SharePoint站点,需使用Graph API的直接上传端点,格式如下:
PUT /sites/{site-id}/drive/items/{parent-item-id}:/{file-name}:/content
{site-id}:目标SharePoint站点的ID{parent-item-id}:文件要上传到的父文件夹ID(根文件夹可填root){file-name}:上传后显示的文件名
2. 修正请求头
保留身份验证头,替换Content-Type为对应文件的MIME类型:
- 移除
Content-Type: application/json - 新增匹配文件类型的
Content-Type:比如XLSX文件用application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,普通文本文件用text/plain等 - 保留
Authorization: Bearer {你的访问令牌}
3. 请求体格式
直接将文件的二进制内容作为请求体发送,不需要包装成任何JSON结构。
Python代码示例(适配Azure环境)
如果后续用Python生成文件并上传,可参考以下代码(本地文件上传示例,生成文件时可直接用二进制流替代本地文件读取):
import requests import io import pandas as pd # 配置参数 site_id = "your-site-id" parent_folder_id = "root" # 根文件夹,或指定文件夹ID file_name = "generated_data.xlsx" access_token = "your-access-token" # 示例:用pandas生成XLSX二进制内容(替换成你的生成逻辑) df = pd.DataFrame({"col1": [1, 2, 3], "col2": ["a", "b", "c"]}) output = io.BytesIO() df.to_excel(output, index=False) output.seek(0) file_content = output.read() # 构建请求 url = f"https://graph.microsoft.com/v1.0/sites/{site_id}/drive/items/{parent_folder_id}:/{file_name}:/content" headers = { "Authorization": f"Bearer {access_token}", "Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" } # 发送请求 response = requests.put(url, headers=headers, data=file_content) # 响应处理 if response.status_code in (200, 201): print("文件上传成功") else: print(f"上传失败:{response.json()}")
注意事项
- 确保你的访问令牌拥有
Files.ReadWrite或Sites.ReadWrite.All的权限 - 生成文件时,直接使用二进制流可以避免本地文件IO,更适合Azure云环境
内容的提问来源于stack exchange,提问作者Hannu Sihvonen
相关产品推荐
相关产品推荐

