How to encode a PDF file to base64 in groovy?
Hi, I am using below script to encode a PDF file. However, file gets corrupted when decoding or an API uploads it to a specific location.
Can you please point out if there is a better way or correct way to encode a PDF file using groovy script.
import net.sf.*
import groovy.io.FileType
//## Get Directories ##//
def projectPath = context.expand('${projectDir}')
def filePath = context.expand( '${#Project#TestDataPath}' )
def docName = context.expand( '${#TestCase#fileName}' )
//## get file ##//
log.info "get pdf from $dumpFilePath"
testFile = new File(filePath + "$docName").text
//Encode file to Base64 format
log.info "Encoding the file..."
encodedFile = "$testFile".getBytes("UTF-8").encodeBase64().toString()
log.info "Updating encoded file at testCase level property testFile"
testRunner.testCase.setPropertyValue("testFile", "$encodedFile")
I also tried - encodedFile = "$testFile".bytes.encodeBase64().toString(). But same result.
TIA.
richie, that's what even I thought too. couldn't find any groovy native function to do this. but ended up using Java snippet.
Here is the updated code:
import java.io.File
import java.nio.file.Files
import java.util.Base64//## Get Directories ##//
def dumpFilePath = context.expand( '${#Project#TestDataPath}' )
def docName = context.expand( '${#TestCase#fileName}' )
//## Encode file to Base64 format ##//
log.info "get pdf file from $dumpFilePath"
testFile = new File(dumpFilePath + "$docName")log.info "Encoding the file..."
byte [] bytes = Files.readAllBytes(testFile.toPath())
String encodedFile = Base64.getEncoder().encodeToString(bytes)log.info "Updating encoded file at testCase level property testFile"
testRunner.testCase.setPropertyValue("testFile", "$encodedFile")