Hi,
Currently, I am request to write a simple Bonita application to let user see and download files from a specific folder on our Bonita server.
The application web page with automatically display a list of sub-folder and files, which I have already done by writing a REST API extension to load the list of directories and files from the target folder and return as JSON string to display in the web page.
For the next step, I need to make the file name in page into a link that users can click and download the file.
I plan to write a REST API extension that accept 2 parameter directory and file name, and return the file.
The code for getting the file is simple as below:
final ENV_DIR = System.getenv(SETTING_FOLDER_PATH);
def fullpath = ENV_DIR + "\\" + directory + "\\" + filename;
def file = new File(fullpath);
However, I don't know what to to do next, as all of the sample I saw is return JSON string, not file.
Can anyone help me with this?
1 Like
Hi,
Currently, returning a file is very limited with REST API Extension (using the application/octet
content type is not supported).
The supported use case is to return a text file (only) like this:
return responseBuilder.with {
withAdditionalHeader("Content-Disposition","attachment; filename=filename.txt")
withAdditionalHeader("Content-Language", "fr") // Optional
withResponseStatus(HttpServletResponse.SC_OK)
withResponse(fileContentAsString) // fileContentAsString is a String
build()
}
HTH
Romain
After some tries, I have manage to do it by simply convert the content of the file to base24 string, and attach it into a JSON string and send it back.
On the form, a javascript code with get the JSON string and revert it back into a file and return.
REST API code:
def inputFile = new File(folder, filename);
String data = Files.probeContentType(inputFile.toPath());
byte[] content= Files.readAllBytes(inputFile.toPath());
String base64str = DatatypeConverter.printBase64Binary(content);
def json = new groovy.json.JsonBuilder();
json (
filename: filename,
data: data,
content: base64str
)
javascript code:
var setting = [];
var urlGet = "../API/extension/FileDownload?directory=AAA&filename=BBB.pdf";
const httpGet = new XMLHttpRequest();
httpGet.open('GET', urlGet, false);
httpGet.send();
var returnText = httpGet.responseText;
var returnStatus = httpGet.status;
if(returnStatus == "200"){
setting = JSON.parse(returnText);
}
if(setting != undefined && setting != null ){
var filename = setting.filename;
var data = setting.data;
var content = setting.content;
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:' + data + ';base64,' + content;
hiddenElement.target = '_blank';
//provide the name for the file to be downloaded
hiddenElement.download = filename;
hiddenElement.click();
}
What about zip file? Is it possible to zip the file then return? Because the files I need to handle will be document file, includes pdf, Word, Excel,etc.