Problem Statement

In this article, we are showcasing how to convert a base64 string into a file attachment to be conveniently downloaded as an attachment.


Figure 1: Sample Showcase Form Design to Convert Base64 String Into a File Upload Attachment

Here's the code that is placed in the form's Post Form Submission Processing to perform the conversion.

Reading Base64 string from form data and saving it as file attachment in File Upload field
import org.joget.apps.form.service.FileUtil;
import org.joget.commons.util.SetupManager;
import org.joget.commons.util.LogUtil;
import java.util.Base64;
import org.joget.apps.form.model.FormRow;
import org.joget.apps.form.model.FormRowSet;
import org.springframework.context.ApplicationContext;
String formDefId = "request";
String fileName = "#form.request.file_name#";
String tableName = "request";
String id = "";
String formUploadField = "attachment";

//generate file from base64
String base64String = "";
byte[] data = Base64.getDecoder().decode(base64String);

//store pdf
String path = FileUtil.getUploadPath(tableName, id);
final File file = new File(path + fileName);
try {
    //save the file into default folder
    FileUtil.storeFile(file, tableName, tableName);
    FileUtils.writeByteArrayToFile(file, data);
    //file saved successfully, update the form record to store the file name
    ApplicationContext ac = AppUtil.getApplicationContext();
    AppService appService = (AppService) ac.getBean("appService");
    AppDefinition appDef = AppUtil.getCurrentAppDefinition();
    FormRowSet set = appService.loadFormData(appDef.getAppId(), appDef.getVersion().toString(), formDefId, id);
    FormRow row = set.get(0);
    row.put(formUploadField, fileName);
    set.add(0, row);
    appService.storeFormData(appDef.getAppId(), appDef.getVersion().toString(), formDefId, set, id);
} catch (IOException ex) {
    LogUtil.error("base64ToPDF App", ex, "Cannot generate file");

Download Showcase App


  • No labels