T
T
TechNOIR2022-02-15 19:40:51
PHP
TechNOIR, 2022-02-15 19:40:51

Powershell. How to send an image to WEB API?

Hello!

You need to upload an image to the API.
Everything works fine through Postman. I select form-data, specify username (text) and image (image file).
But now it must be done through Powershell (5)
I tried this, but it doesn’t work (

$Headers = @{
    "Auth-Token" = "jD9mGkRSGDFF575474OeBoi6bp"
    "User-Id" = "8234965283592"
}

$Uri = 'https://site.com/api/setAvatar';
$FileContent = [IO.File]::ReadAllBytes('C:Temp\test.png');
$Fields = @{'username'='a.sidorov';'image'=$($FileContent)};
Invoke-RestMethod -Uri $Uri -ContentType 'multipart/form-data' -Method Post -Headers $Headers -Body $Fields;


Please tell me how to do it right? thanks in advance

Answer the question

In order to leave comments, you need to log in

3 answer(s)
O
Olgeir, 2016-03-01
@Olgeir

does it bother you that there are no Russian letters in [a-z0-9_-]?

W
Walt Disney, 2016-02-28
@ruFelix

"~regexp~iu" - you need to add the u modifier , which means utf8.
and, accordingly, check that the source and the string coming for verification are in utf8

V
Vasily Bannikov, 2022-02-15
@TechNOIR

Try this: https://stackoverflow.com/questions/22491129/how-t...

$ErrorActionPreference = 'Stop'

$fieldName = 'file'
$filePath = 'C:\Temp\test.pdf'
$url = 'http://posttestserver.com/post.php'

Try {
    Add-Type -AssemblyName 'System.Net.Http'

    $client = New-Object System.Net.Http.HttpClient
    $content = New-Object System.Net.Http.MultipartFormDataContent
    $fileStream = [System.IO.File]::OpenRead($filePath)
    $fileName = [System.IO.Path]::GetFileName($filePath)
    $fileContent = New-Object System.Net.Http.StreamContent($fileStream)
    $content.Add($fileContent, $fieldName, $fileName)

    $result = $client.PostAsync($url, $content).Result
    $result.EnsureSuccessStatusCode()
}
Catch {
    Write-Error $_
    exit 1
}
Finally {
    if ($client -ne $null) { $client.Dispose() }
    if ($content -ne $null) { $content.Dispose() }
    if ($fileStream -ne $null) { $fileStream.Dispose() }
    if ($fileContent -ne $null) { $fileContent.Dispose() }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question