I am new to Powershell and having trouble sending a file via an HTTP POST request. Everything is working perfectly except for sending/uploading the file. Is this possible using my existing code?
Here is my code:
# VARIABLES
$myFile = "c:\sample_file.csv"
$updateUrl = "http://www.example.com/processor"
$postData = "field1=value1"
$postData += "&field2=value2"
$postData += "&myFile=" + $myFile
# EXECUTE FUNCTION
updateServer -url $updateUrl -data $postData
function updateServer {
param(
[string]$url = $null,
[string]$data = $null,
[System.Net.NetworkCredential]$credentials = $null,
[string]$contentType = "application/x-www-form-urlencoded",
[string]$codePageName = "UTF-8",
[string]$userAgent = $null
);
if ( $url -and $data ){
[System.Net.WebRequest]$webRequest = [System.Net.WebRequest]::Create($url);
$webRequest.ServicePoint.Expect100Continue = $false;
if ( $credentials ){
$webRequest.Credentials = $credentials;
$webRequest.PreAuthenticate = $true;
}
$webRequest.ContentType = $contentType;
$webRequest.Method = "POST";
if ( $userAgent ){
$webRequest.UserAgent = $userAgent;
}
$enc = [System.Text.Encoding]::GetEncoding($codePageName);
[byte[]]$bytes = $enc.GetBytes($data);
$webRequest.ContentLength = $bytes.Length;
[System.IO.Stream]$reqStream = $webRequest.GetRequestStream();
$reqStream.Write($bytes, 0, $bytes.Length);
$reqStream.Flush();
$resp = $webRequest.GetResponse();
$rs = $resp.GetResponseStream();
[System.IO.StreamReader]$sr = New-Object System.IO.StreamReader -argumentList $rs;
$sr.ReadToEnd();
}
}