Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading file to HTTP via Powershell

We have a php site that uploads pictures to server, simple jpg file with correct naming. Problem is that we need to upload sometimes couple of hundred of them at a time, but php accepts only 1 at a time, renames them and uploads. I have done file operations in PS quite well, but fail to upload.

PHP part related to upload (as far as I can tell) looks like this: <form name='' id='' enctype='multipart/form-data' method='POST' action='/picture_upload.php' target='_self' onsubmit="default_on_submit(event)">

I checked Google, related topics here as well, and got to this:

$uri = "http://example.com/"
$pwd = ConvertTo-SecureString 'MyPassword' -AsPlainText -Force
$cred = New-Object Management.Automation.PSCredential ('myuser', $pwd)
$contentType = "multipart/form-data"
    $body = @{
        "FileName" = Get-Content($uploadPath) -Raw
    }
    Invoke-WebRequest -Uri $uri -Method Post -ContentType $contentType -Body $body

I have checked $uploadPath and it is correct C:\Folder\file.jpg. I use credentials that I use to log in to site where I can upload these pictures via GUI.

I have tried switching between POST and PUT, with no changes.

Replacing http://example.com with http://example.com/file.jpg also provided no difference. Unsure, which is correct way to use POST.

We have McAffe web gateway in company, but I'm running script with user that bypasses it, so it's not causing this.

Current error message that I'm getting is: "Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a receive."

Any help would be greatly appreciated! And sorry if this has been already solved and I've simply missed an entry!

P.S. I have also tried this - Powershell script to Upload log file from local system to http URL, and it returns Exception calling "UploadFile" with "3" argument(s): "An exception occurred during a WebClient request."

like image 849
Kārlis Bergmanis Avatar asked Jul 02 '16 21:07

Kārlis Bergmanis


1 Answers

A year late, so you probably don't need the answer anymore, but what worked for me was:

Invoke-RestMethod -Uri $uri -Method Post -InFile $uploadPath -UseDefaultCredentials

Mine needed to use windows auth as the currently logged in user... From this other answer, looks like you can use -cred in some cases and have to build out an Authorization header in others.

like image 60
superlime Avatar answered Oct 15 '22 13:10

superlime