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.

Solution

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 java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
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.app.model.AppDefinition;
import org.joget.apps.app.service.AppService;
import org.joget.apps.app.service.AppUtil;
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 = "#form.request.id#";
String formUploadField = "attachment";

//generate file from base64
String base64String = "#form.request.data#";
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.remove(0);
    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

APP_base64ToFile-1-20230124121825.jwa

  • No labels