Convert Base64 String to File

Introduction

In this article, you'll learn how to convert a base64 string into a file attachment that can be conveniently downloaded. This approach is useful for transforming encoded data into a usable file format within a form submission.

How does it work?

The process involves reading the base64 string from the form data, decoding it, and saving it as a file attachment. The code provided is placed in the form's Post Form Submission Processing to perform the conversion. This method ensures that any base64 encoded data can be converted into a file and attached to the form submission, making the data easily accessible and downloadable.

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

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 sample app

Download the demo app for converting a base64 string to a file:
Created by Julieth Last modified by Aadrian on Dec 13, 2024