Sunday, November 19, 2017

Upload File To REST API, Using Windows PowerShell (Content Type: x-www-form-urlencoded)

A REST API (e.g. WebAPI) can accept file contents using mime type (x-www-form-urlencoded) format. An implementation with WebAPI has been mentioned here.

Now you can use a PowerShell script to upload a file to such a REST API. The below given powershell script demonstrates this idea.

The script takes a drop folder with JSON files and the REST Url, which accept the file in (x-www-form-urlencoded) format. The json files inside the folder will be picked one by one and posted to the REST Url.

The complete example (Including REST API with a WebAPI implementation) can be downloaded from here.

#

# Usage eg: UploadJsonDocuments.ps1 -jsonsFolder ".\Documents" -uploadApiUrl "http://localhost:50153/api/upload"

#

param(

[string]$jsonsFolder = ".\Documents",

[string]$uploadApiUrl = "http://localhost:50153/api/upload")

$dropFolder = $jsonsFolder

$url = $uploadApiUrl

Add-Type -AssemblyName System.Web

Get-ChildItem "$dropFolder"-Filter *.json | Foreach-Object {

$docContent = Get-Content -Path $_.FullName

$body = "=" + [System.Web.HttpUtility]::UrlEncode($docContent)

$hdrs = @{}

Try

{

$currentDoc = $_.Name

$response = (Invoke-RestMethod -Uri $url -Method Post -Body $body -ContentType 'application/x-www-form-urlencoded; charset=UTF-8' -Headers $hdrs -UseDefaultCredentials 2> $null)

Write-Output "$currentDoc->OK ($response)"

}

Catch

{

$ErrorMessage = $_.Exception.Message

Write-Output "$currentDoc->Failed ($ErrorMessage)"

Break

}

}