Home > database >  Upload large file to SharePoint Online using Graph API - ContentType error
Upload large file to SharePoint Online using Graph API - ContentType error

Time:07-05

I am looking for a way to upload large files (over 4MB) to SharePoint Online using PowerShell and Graph API. I am able to upload files <4MB in size without any problems, but I am struggling with larger files.

I am trying to use this solution but the following part (line 105, when trying to upload the file) is not working for me:

$invokeRestMethodParams = @{
    Uri     = $uploadUrl
    Method  = "PUT"
    Headers = @{
        Accept           = "application/json"
        "Content-Type"   = "text/plain"
        Authorization    = "bearer $($token)"
        "Content-Length" = $fileLength
        "Content-Range"  =  "bytes 0-$($fileLength-1)/$($fileLength)"
    }
    Body = $fileInAscii
}

$response = Invoke-RestMethod @invokeRestMethodParams

I keep getting the following error on the Invoke-RestMethod (everything else before that works fine):

The cmdlet cannot run because the -ContentType parameter is not a valid Content-Type header. Specify a valid Content-Type for -ContentType, then retry. To suppress header validation, supply the -SkipHeaderValidation parameter.

If I use the -SkipHeaderValidation parameter, I get the following error:

Response status code does not indicate success: 400 (Bad Request).

I've tried different types of files (they are all less than 10MB) like TXT or PDF, and even different ContentTypes like "application/octet-stream" or "text/plain", but nothing seems to work... I've also tried another solution I found online (this one), but the error was the same.

Is anyone else experiencing the same, or do you have a script to upload large files (over 4MB) to SharePoint Online using PowerShell AND Graph API? Thank you so much!

Regards, Nuno

CodePudding user response:

I've managed to find a simpler solution that works for files over 3MB (I've also tested 100MB size files). To get the upload URL, I used the code from the solution in my first post.

    $fileInBytes = [System.IO.File]::ReadAllBytes($file)
    $fileLength = $fileInBytes.Length

    $invokeRestMethodParams = @{
        Uri     = $uploadUrl
        Method  = "PUT"
        Body    = $fileInBytes
        Headers = @{
            'Content-Range' = "bytes 0-$($fileLength-1)/$fileLength"
        }
    }

    Try {
        $response = Invoke-RestMethod @invokeRestMethodParams -ErrorAction Stop
        Write-Log -Type "INF" -Message "File uploaded to SharePoint Online: '$fileName' ($([Math]::Round($file.length/1MB, 0))MB)"
    } Catch {
        Write-Log -Type "ERR" -Message "Unable to upload '$fileName' to SharePoint Online: '$($_.Exception.Message)'"
    }
  • Related