Lilith Mae
Lilith Mae

Reputation: 132

Powershell Rest API- Encode PDF to B64

I'm having an issue trying to get this to work. What I'm trying to do is upload a "PDF" to our system using API commands in Powershell. I've been able to upload "documents" from my disk drive, but when I try to view them they are either "Document not found" or "Cannot open this PDF" or ""The input is not a valid Base-64 string as it contains a non-base 64 character". I've tried different methods: encoding/decoding in a variety of ways, I've tried opening it in several different programs- doesn't seem like nothing is working and I'm losing sleep.

Below is my code for just straight upload:

$fileName = "C:\files\Test1.pdf"
$data = ConvertTo-Json @{

encrypted="false";
allowSaveBinaryData="True";
binaryData=$fileName;
divider="Expense Report";
isMultipageImage="true";
extension="pdf";
name="Test1.pdf";
relProjectId="31";
}

$addproject="https://ENDPOINT URL.com/v4/documents/597?guid=$temp&fbsite=https://MYURL.com/"


Invoke-RestMethod -ContentType 'application/json' -Method PUT -Body $data -Uri $addproject

Below is my code I tried using encoding/decoding:

$fileName = "C:\files\Test1.pdf"
$fileContent = get-content $fileName
$fileContentBytes = [System.Text.Encoding]::Unicode.GetBytes($fileContent)
$fileContentEncoded = [System.Convert]::ToBase64String($fileContentBytes)

$data = ConvertTo-Json @{

encrypted="false";
allowSaveBinaryData="True";
binaryData=$fileContentEncoded;
divider="Expense Report";
isMultipageImage="true";
extension="pdf";
name="Test1.pdf";
relProjectId="31";
}

$addproject="https://ENDPOINT URL.com/v4/documents/597?guid=$temp&fbsite=https://MYURL.com/"


Invoke-RestMethod -ContentType 'application/json' -Method PUT -Body $data -Uri $addproject

Upvotes: 1

Views: 2556

Answers (1)

Lilith Mae
Lilith Mae

Reputation: 132

I've figured it out with this::

$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Accept", 'application/pdf')

$fileName="C:\files\$item2"
$fileContent = get-content -Raw $fileName
$fileContentBytes = [System.Text.Encoding]::Default.GetBytes($fileContent)
$fileContentEncoded = [System.Convert]::ToBase64String($fileContentBytes)


$data = ConvertTo-Json @{

encrypted="false";
allowSaveBinaryData="true";
binaryData="$fileContentEncoded"
divider="Expense Report";
extension="pdf";
name="$fileContentEncoded";
relProjectId="31";
fileID="597"
}

$var2[$i2]="https://MY ENDPOINT /v4/documents/597?guid=$AUTHtemp&fbsite=https://XXXXXXXXX/"

Invoke-RestMethod -headers $headers -ContentType 'application/json' -Method PUT -body $data -Uri $var2[$i2]}

Upvotes: 2

Related Questions