2

I am trying to upload a file to a URL. I have tried both these approaches:

Invoke-RestMethod -Uri $uploadUrl -Method Put -Headers $uploadHdrs -InFile $uploadFilePath

Invoke-RestMethod -Uri $uploadUrl -Method Put -body $uploadFileBody -Headers $uploadHdrs

Error I am getting:

Invoke-RestMethod : You must write ContentLength bytes to the request stream
before calling [Begin]GetResponse.

If I add in the -TransferEncoding param, I get errors from the server saying unsupported.

What can I do to include the content length?

Burt_Harris
  • 6,415
  • 2
  • 29
  • 64
irl_irl
  • 3,785
  • 9
  • 49
  • 60
  • 1
    What's in `$uploadHdrs`? – Janne Tuukkanen Feb 09 '18 at 20:22
  • content-md5 header. I get the same error if I exclude the headers param – irl_irl Feb 10 '18 at 12:26
  • 1
    Please show the contents of `$uploadFileBody`. If it's a raw file, then this might help: https://stackoverflow.com/questions/42395638/how-to-use-invoke-restmethod-to-upload-jpg – Ruud Helderman Feb 11 '18 at 19:54
  • The answer marked is to use inFile. As in the question, that has the same problem. With infile $uploadFilePath is a filepath and with the body param, it is [System.IO.File]::ReadAllBytes("path_to_the_file") – irl_irl Feb 11 '18 at 20:08
  • Have you tried `$uploadFileBody = Get-Content $uploadFilePath` ? – gvee Feb 12 '18 at 09:14
  • -inFile requires a string param and -body Invoke-RestMethod : You must write ContentLength bytes to the request stream before calling [Begin]GetResponse. – irl_irl Feb 12 '18 at 16:11
  • I wonder if this is a limitation within `Invoke-RestMethod`? Have a try swapping to `Invoke-WebRequest` instead... – gvee Feb 13 '18 at 13:55
  • Yeah, I have. I've also tried [net.WebRequest]::Create($uploadUrl) rather than using the invoke commands. – irl_irl Feb 13 '18 at 14:37

1 Answers1

1

I think you'll need to use a different command, like Invoke-WebRequest or even better call the .NET WebClient.UploadFile() or .UploadData methods directly from PowerShell.

While REST methods might conceptually include uploading files, that doesn't mean that the Invoke-WebRequest command has been tested as supporting your scenario. I'd suggest going lower-level (like WebClient) because we know more scenarios have been tested (by the larger .NET team), and there are a wide variety of methods on WebClient for supporting specific scenarios.

One example you might find helpfull in how to invoke these methods from PowerShell is at https://social.technet.microsoft.com/Forums/windowsserver/en-US/0c268c7e-674c-49bc-9933-a87a95f8f44c/powershell-webclientuploadfile?forum=winserverpowershell

P.S. The message your are getting about the request stream is coming from an even lower level .NET API, but WebClient is simpler to use, should take care of setting ContentLength properly and hopefully is "just right" for your need.

Burt_Harris
  • 6,415
  • 2
  • 29
  • 64