File upload with API and PowerShell failing

Just to close off this problem, and for the benefit of anyone else who has this issue now, or in the future, I managed (with a lot of back-and-forth) to get this working with the following bit of PowerShell:

$File = "C:\path\to\file\to\upload.txt"

# Get just the file name (no path)
$FileName = Split-Path $File -leaf
	
# Get a GUID that is used to indicate the start and end of the file in the request
$boundary = "$([System.Guid]::NewGuid().ToString())"

# Read the contents of the file
$FileBytes = [System.IO.File]::ReadAllBytes($File)
$FileContent = [System.Text.Encoding]::GetEncoding('iso-8859-1').GetString($FileBytes)

# Build a Body to submit the request
$bodyLines = @"
--$boundary
Content-Disposition: form-data; name=`"`"; filename=`"$FileName`"
Content-Type: application/octet-stream

$FileContent
$($boundary)--
"@

Invoke-RestMethod -URI https://myserver:52311/api/upload -Method 'POST'  -ContentType "multipart/form-data; boundary=`"$boundary`"" -Body $bodyLines -Credential $creds

This is probably not the most optimal way of doing it as it requires that the entire file is read in to memory but it’s worked for me for whatever I’ve thrown at it (EXEs, MSIs, TXTs)

2 Likes