In many Pega applications, there are scenarios where files are generated dynamically and stored temporarily on the server. Users may then need to download these files directly from the application UI. One practical approach is to create a custom Activity that reads the file from the server path and streams it to the browser for download.
This blog explains how to implement file download functionality in Pega using Java steps inside an Activity.
Use Case
Suppose your application:
- Generates PDF reports
- Creates Excel exports
- Produces temporary documents on the server
- Stores files in a shared directory
You can allow users to download these files directly using a Pega Activity.
Solution Overview
The implementation works as follows:
- Pass the server file path as a parameter
- Read the file from the server
- Convert the file into a byte array
-
Use
tools.sendFile()to stream the file to the browser - Optionally delete the file after download
Add a Java Step
Add a Java step inside the Activity and use the following code
Java used for this activity
``` //Get the byte array from the parameter page
//String Stream=tools.getParamValue("FileStream");
FilePath = tools.getParamValue("FilePath");
//byte[] byteArray=Base64Util.decodeToByteArray(Stream);
java.io.File originalFile = new java.io.File(FilePath);
java.io.FileInputStream fileInputStreamReader=null;
byte[] bytes=null;
try{
if(originalFile.exists())
{
fileInputStreamReader = new java.io.FileInputStream(originalFile);
bytes = new byte[(int)originalFile.length()];
fileInputStreamReader.read(bytes);
fileInputStreamReader.close();
}
else{
ErrMsg="Uanble to open a file/file dooesn't exist:"+FilePath;
}
}
catch(Exception ex){
oLog.error("Error during opening the document in ProcessAutoCreateDocument activity:"+ex.getMessage());
ErrMsg=ex.getMessage();
}
//Get the file name from the parameter page
pdfName=tools.getParamValue("FileName");
// download the file directly
String result=tools.sendFile( bytes,pdfName,false,null,true);
// delete file from path after download
//originalFile.delete();


Post a Comment