upload a file larger than 4mb using ms graph powershell

Damania Harsh 1 Reputation point
2021-09-23T08:33:23.957+00:00

Hi , i am trying to upload an xlsx file larger than 4mb, but it gets corrupted.
Text file works fine

[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

"https://graph.microsoft.com/v1.0/sites/20b44bd9-97fa-4666-b735-6ac0868a04c1/drive/items/01CLOFTIEVJ25ZIZLHKVA3Q3HXB67OWT2G/createUploadSession"

$filePath = "C:\Users\Downloads\"+$filename

Convert the file into ascii code and get the file size in bytes

$fileInBytes = [System.IO.File]::ReadAllBytes($filePath)
$fileInAscii = [System.Text.Encoding]::ASCII.GetString($fileInBytes)
$fileLength = $fileInAscii.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")

$body = $fileInAscii

$responseUpload = Invoke-RestMethod $responseCreateUploadSession.uploadUrl -Method 'PUT' -Headers $headersNew -Body $body

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
10,669 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. MichaelHan-MSFT 18,016 Reputation points
    2021-09-24T09:57:36.223+00:00

    Hi @Damania Harsh ,

    The body should be in bytes to upload the file:

    $body = $fileInBytes  
    

    If an Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.