You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用MS Graph API(Python)上传至SharePoint的PDF无法打开问题

问题解决:MS Graph API上传PDF到SharePoint无法预览

你的问题出在不必要的Base64编码——MS Graph的/content端点需要直接接收原始二进制文件内容,而你上传的是Base64编码后的字符串,导致SharePoint存储的不是有效PDF文件,自然无法读取或预览。

修正后的代码

  1. 直接读取二进制文件内容,无需Base64转换:
with open(pdf_filename, "rb") as pdf_file:
    pdf_content = pdf_file.read()  # 直接获取二进制数据
  1. PUT请求直接传入二进制内容:
response_upload = requests.put(
    f"https://graph.microsoft.com/v1.0/sites/{site_id}/drive/root:/Document Folder/PDF_Name.pdf:/content",
    data=pdf_content,
    headers=headers
)
  1. 请求头保持不变即可:
headers = {'Authorization': 'Bearer {}'.format(token), "Content-Type":"application/pdf"}

额外检查项

  • 确认响应状态码:上传成功后应返回201 Created或200 OK,可通过response_upload.status_code查看
  • 验证本地PDF文件本身是否正常可打开,排除文件损坏问题
  • 确保你的访问令牌拥有Files.ReadWrite或更高权限

内容的提问来源于stack exchange,提问作者NLang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 06:22:45