Uploading large files to SharePoint Online

I’ve uploaded many files to SharePoint 2013 Online over the last couple of years, all these files have been pretty small.  These files have been uploaded via PowerShell scripts.

The other day I needed to upload a slightly larger file (more then 2MB) and got the following issue:

The request message is too large. The server does not allow messages that are larger than 2097152 bytes.

Previously I was uploading files in the following way:

function Add-FileToSpLib($file)
{
	$filePath = Get-ChildItem $file	
	$fileBytes = [System.IO.File]::ReadAllBytes($filePath.FullName)
	$fileinfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
	$fileinfo.Content = $fileBytes
	$fileinfo.Url = $library.RootFolder.ServerRelativeUrl + "/" + $filePath.Name
	$fileinfo.Overwrite = $true
	$newFile = $library.RootFolder.Files.Add($fileinfo)
	

	$ctx.Load($newFile)
	$ctx.ExecuteQuery()
}

The above function caused issues when the file was larger than 2MB.

Using the method below I was able to workaround this issue:

	$CurrentList = $ctx.Web.Lists.GetByTitle("My Library");
	$ctx.Load($CurrentList.RootFolder);
	$ctx.ExecuteQuery();


	$filePath = 'C:\Files\fileToUpload.txt'
	$stream  = New-Object IO.FileStream $filePath ,'Open'
	
	
	[Microsoft.SharePoint.Client.File]::SaveBinaryDirect($ctx, $CurrentList.RootFolder.ServerRelativeUrl.ToString() + “/” + $filePath.Split(‘\\’)[2], $stream, $true);
	$stream111.Close()

More info on the SaveBinaryDirect method:

https://msdn.microsoft.com/EN-US/library/office/microsoft.sharepoint.client.file.savebinarydirect.aspx