I am making this call (simplified for clarity):
Invoke-WebRequest -Uri https://myserver:52311/api/upload -Method POST -InFile C:\Temp\File.txt -Credential $creds
but get this error:
Invoke-WebRequest : Files were not supplied in request body
Any idea what I am doing wrong? Searching for that error turns up nothing. Reading around how to upload files with Invoke-WebRequest suggests that this command is correctly formatted. Is there a parameter or something that I am missing?
As per documentation
"For uploading a single file you can specify the filename in the content-disposition header and send the file as the body",
that is you have to add a new header to your POST command Content-Disposition: attachment; filename="File.txt"
and put the content of C:\Temp\File.txt in the body of the request.
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)
I’ll try later on my machine - I’ve found the following example with Invoke-RestAPI - https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-restmethod
Look into Example 4: Simplified Multipart/Form-Data Submission
It mentioned that , If a System.IO.FileInfo value is present, the file contents will be submitted.
By using Get-Item …, the FileInfo object will be set as the value. The result is that the image data for jdoe.png will be submitted.