Base64 EncodingPremium
Use the encodeBase64 function when you need to turn string content that may contain non-ASCII characters (accented letters, Cyrillic, and CJK characters) into a data URI that saveAs can consume.
saveAs expects file content as a data URI or a Blob. A data URI embeds the file content directly in the URL. When you use encodeBase64, include the ;base64 marker and Base64-encoded content.
Encode a string with encodeBase64 and prefix it with a MIME type to build a data URI, then pass it to saveAs.
import { saveAs, encodeBase64 } from '@progress/kendo-file-saver';
const dataURI = "data:text/plain;base64," + encodeBase64("Hello World!");
saveAs(dataURI, "hello.txt");
The
encodeBase64function encodes strings only. For binary data, such as PDF or XLSX bytes in aUint8Array, convert the bytes to a binary string before using the built-inbtoafunction. Alternatively, pass aBlobdirectly tosaveAswhen no server proxy is active.
Data URI Construction
A data URI has the following structure:
data:<mediatype>;base64,<data>
Choose the media type that matches the file you are saving:
| File type | Media type |
|---|---|
| Plain text | text/plain |
| CSV | text/csv |
| HTML | text/html |
| JSON | application/json |
| XML | application/xml |
For JSON, stringify the object before encoding:
import { saveAs, encodeBase64 } from '@progress/kendo-file-saver';
const json = JSON.stringify({ name: "Alice", score: 42 }, null, 2);
const dataURI = "data:application/json;base64," + encodeBase64(json);
saveAs(dataURI, "result.json");
The following demo shows how to save JSON content using a base64-encoded data URI.
UTF-8 Content
The browser's built-in btoa function accepts only strings with code units in the U+0000-U+00FF range. It throws an InvalidCharacterError for characters outside that range, including Cyrillic and CJK characters.
The encodeBase64 function converts the input to UTF-8 bytes first, so strings with accented letters, Cyrillic, or CJK characters encode without errors:
import { saveAs, encodeBase64 } from '@progress/kendo-file-saver';
const csv = "Name,City\nJohanna Müller,Düsseldorf\n";
const dataURI = "data:text/csv;base64," + encodeBase64(csv);
saveAs(dataURI, "cities.csv");
Prepend the \uFEFF BOM character to the content before encoding it to ensure Excel opens the file with the correct encoding:
const dataURI = "data:text/csv;base64," + encodeBase64("\uFEFF" + csv);
The following demo shows how to save CSV content with UTF-8 encoding using a base64-encoded data URI.