Triggering File Download From The Browser By Using A Base64 Encoded File Content



You have a service that consists of frontend and API applications. In order to prove the result of a process, you need to generate a PDF file that the user can download from the frontend application. The frontend application would create the file by using the base64-encoded content received from the API.


For the sample code, let’s assume that we have the file content in base64EncodedData variable.

const base64EncodedData = // BASE64 encoded file content...

Create an anchor element.

const downloadLink = document.createElement(‘a’);

Set the base64-encoded content and the output filename for the file to be downloaded.

const linkData = `data:application/pdf;base64,${base64EncodedData}`;
downloadLink.href = linkData; = fileName;

And… trigger download;

Let’s put everything together.

That’s it.