PowerShell version 5.1 upload file along with string data in form

function UploadFileToScan {
    param (
        $Path
    )
    
    Add-Type -AssemblyName System.Net.Http

    try {
        $client = [System.Net.Http.HttpClient]::new()
        $request = [System.Net.Http.HttpRequestMessage]::new([System.Net.Http.HttpMethod]::Post, $yaraifyApiUrl)
        $content = [System.Net.Http.MultipartFormDataContent]::new()
        $fileContent = [System.IO.File]::OpenRead($Path)
        $fileName = [System.IO.Path]::GetFileName($Path)
        $fileStream = [System.Net.Http.StreamContent]::new($fileContent)
        $stringData = [System.Net.Http.StringContent]::new("{""clamav_scan"": 1,""unpack"":1, ""share_file"": 0,""skip_noisy"":1}")

        $content.Add($fileStream, "file", $fileName)
        $content.Add($stringData, "json_data")

        $request.Content = $content

        Write-Host "Uploading..." -NoNewline

        $response = $client.SendAsync($request).Result
        $response.EnsureSuccessStatusCode() | Out-Null
        $result = $response.Content.ReadAsStringAsync().Result

        Write-Host "Done"

        return $result
    }
    catch {
        Write-Error "Failed. $($_)"
    }
}
创建时间:5/27/2023 12:28:44 AM 修改时间:5/27/2023 12:29:17 AM