Search code examples
powershelljenkinspostparametersmultipartform-data

Upload file to Jenkins through HTTP Request


I have a Jenkins Job that requires a file as parameter (I'm using the file parameter plugin). When I made the call to Jenkins I notice that the file parameter doesn't get sent but the other parameters do (CHOICE and string), what I'm doing wrong?

$credPair = "user:token";
$encodedCredentials = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($credPair));
$headers = @{
    "Authorization" = "Basic $encodedCredentials";
    "Content-Type" = "multipart/form-data";
}

$choiceParam = "option"
$stringParam = "value"
$file = "file_path"
$Body = @{ "File" = [IO.File]::ReadAllText($file); }

$url = "https://server/job/buildWithParameters?CHOICE=" + $choiceParam + '&string' + $stringParam

try {
    Invoke-RestMethod -Uri $url -Headers $headers -Method Post -Body $Body
}
catch {
    Write-Host "StatusCode: " $_.Exception.Response.StatusCode.value__
    Write-Host "StatusDescription: " $_.Exception.Response.StatusDescription
    write-host "Error details: " $_.ErrorDetails.Message
    exit
}

I already tried the next questions and didn't work multipart/form-data file upload with PowerShell powershell invoke-restmethod multipart/form-data How to send multipart/form-data with PowerShell Invoke-RestMethod Using PowerShell Invoke-RestMethod to POST large binary multipart/form-data

I want to send a file parameter to Jenkins via HTTP Post Request with PowerShell


Solution

  • @zett42 I solve it, apparently only in the form you put the file, the others params are put in the url

    $credPair = "user:token";
    $encodedCredentials = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($credPair));
    $headers = @{
        "Authorization" = "Basic $encodedCredentials";
    }
    
    $choiceParam = "option"
    $stringParam = "value"
    $file = "file_path"
    
    $form = @{
        INSERT_NAME_OF_FILE_PARAM = Get-Item $file
    }
    
    $url = "https://server/job/INSERT_JOBNAME/buildWithParameters?INSERT_NAME_OF_CHOICE_PARAM=" + $choiceParam + '&INSERT_NAME_OF_STRING_PARAM=' + $stringParam
    
    try {
        Invoke-RestMethod -Uri $url -Headers $headers -Method Post -Form $form
    }
    catch {
        Write-Host "StatusCode: " $_.Exception.Response.StatusCode.value__
        Write-Host "StatusDescription: " $_.Exception.Response.StatusDescription
        write-host "Error details: " $_.ErrorDetails.Message
        exit
    }