使用MS Graph API(Python)上传至SharePoint的PDF无法打开问题
你的问题出在不必要的Base64编码——MS Graph的/content端点需要直接接收原始二进制文件内容,而你上传的是Base64编码后的字符串,导致SharePoint存储的不是有效PDF文件,自然无法读取或预览。
修正后的代码
- 直接读取二进制文件内容,无需Base64转换:
with open(pdf_filename, "rb") as pdf_file: pdf_content = pdf_file.read() # 直接获取二进制数据
- 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 )
- 请求头保持不变即可:
headers = {'Authorization': 'Bearer {}'.format(token), "Content-Type":"application/pdf"}
额外检查项
- 确认响应状态码:上传成功后应返回
201 Created或200 OK,可通过response_upload.status_code查看 - 验证本地PDF文件本身是否正常可打开,排除文件损坏问题
- 确保你的访问令牌拥有
Files.ReadWrite或更高权限
内容的提问来源于stack exchange,提问作者NLang
相关产品推荐
相关产品推荐

