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

Microsoft Graph PowerShell上传大于4MB的xlsx文件失败问题

故障根因

你设置的Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet是正确的,文件损坏的核心原因是代码中对二进制文件做了ASCII转码处理:
xlsx属于二进制格式文件,[System.Text.Encoding]::ASCII.GetString($fileInBytes)会将所有超出ASCII编码范围(0x00-0x7F)的字节强制替换为?字符,直接破坏了原文件的二进制结构;而普通文本类文件的内容大多落在ASCII兼容范围内,所以没有出现损坏问题。

修复方案

调整文件读取和上传逻辑,完全保留文件的原始二进制内容即可,修复后的参考代码如下:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12

$filename = "Test.xlsx"

$api = "https://graph.microsoft.com/v1.0/sites/10b44bd9-97fa-4666-b735-6ac0868a04c1/drive/root:/General/"+$filename+":/createUploadSession"
$responseCreateUploadSession = Invoke-RestMethod $api -Method 'POST' -Headers $Headers

$filePath = "C:\Users\Downloads\"+$filename
# 直接获取原始文件字节,不做任何编码转换
$fileInBytes = [System.IO.File]::ReadAllBytes($filePath)
$fileLength = $fileInBytes.Length
$accesstoken = $Headers.Values

$headersNew = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headersNew.Add("Content-Length", $fileLength)
$headersNew.Add("Content-Range", "bytes 0-$($fileLength-1)/$($fileLength)")
$headersNew.Add("Authorization", $accesstoken)
$headersNew.Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")

# 传递原始字节数组作为请求体,额外设置UseBasicParsing避免不必要的解析
$responseUpload = Invoke-RestMethod $responseCreateUploadSession.uploadUrl -Method 'PUT' -Headers $headersNew -Body $fileInBytes -UseBasicParsing

补充注意事项

  • 如果文件大小超过60MB,建议按要求拆分为最大60MB的分片上传,避免单次请求超时
  • 也可以直接使用Invoke-RestMethod的-InFile参数直接指定本地文件路径,不需要手动读取字节,框架会自动处理二进制内容传输

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 18:30:03