How to Convert Base64 to File in JavaScript?
Last Updated :
30 Aug, 2024
In web development, Base64 encoding is often used to represent binary data, such as images or files, with a string of ASCII characters, sometimes you may be required to change this Base64 string back into a file for instance for file uploads, downloads, or processing in the browser, this article aims to discuss different ways of converting Base64 strings to file objects in JavaScript.
Base64 encoding changes binary data into an ASCII character string. Most frequently it is used in image encoding, data URIs, and file uploads, the purpose of decoding Base64 back to a file is to recover the original binary data in its original form as a file either for processing or download.
Approach: Using Blob API
In this approach, a base64 encoded string that represents an image is converted into a downloadable image file using JavaScript, this process is done in the browser with the help of Blob API and creating a temporary download link to initiate the file download.
Example: This example shows the conversion of Bse64 to a file using JavaScript.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<title>Base64 to Image File</title>
</head>
<body>
<h1>Base64 to Image File Conversion</h1>
<button id="download">Download Image File</button>
<script>
// Function to convert Base64 string to Blob and trigger download
function base64ToFile(base64String, mimeType, fileName) {
// Remove data URL scheme if present
const base64Data = base64String.replace(/^data:.+;base64,/, '');
const byteCharacters = atob(base64Data); // Decode Base64 string
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray], { type: mimeType });
const url = URL.createObjectURL(blob);
// Create a link element to download the file
const link = document.createElement('a');
link.href = url;
link.download = fileName;
link.click();
// Cleanup
URL.revokeObjectURL(url);
}
// Base64 string representing an image (JPEG in this case)
const base64String =
`/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDh
IQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUF
BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUF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nWh2f
NCaLBL1wkiH0INKHmQrt2qrz6mUDIEhBe1j7xijWOwzYgyV1YdmKHuy3/3EFUQim5g00ocUwHQLgE
i44FHziZ3ARRGeWAXmwUYeIdq6AVx+JFE8LZyD4F6n57NBNA9IlyZLoh8V0LzcR4uA72qNPF6YBpKIY9mo
72U5luKgKDfNg8rAbQE3CNBoROaR2hqBYmsY/HuJEXnwD4OsAqpg0cS6JQOwVYoPXoYEnV+LP8ASpk
Sr9w4jatKm+38z//Z`; // Replace with your actual Base64 string
const mimeType = "image/jpeg"; // MIME type for JPEG image
const fileName = "image.jpg"; // Desired file name with extension
document.getElementById('download').addEventListener('click', () => {
base64ToFile(base64String, mimeType, fileName);
});
</script>
</body>
</html>
Output:
Similar Reads
How to Convert Base64 to Blob in JavaScript? Working with files and data in web applications often involves dealing with binary data. One common scenario is converting a Base64 string into a Blob object, which can then be used in various ways, such as creating downloadable files or uploading images to a server. This article will guide you thro
4 min read
How to Convert JSON to base64 in JavaScript ? Base 64 is the encoding scheme that represents binary data in a printable ASCII format, commonly used for data serialization and transmission. Table of Content Using btoa functionUsing Manual ConversionUsing btoa functionIn this approach, we're using btoa to encode a UTF-8 string representation of a
2 min read
How To Convert Base64 to JSON String in JavaScript? There could be situations in web applications, where there is a need to decode the data from Base64 format back into its original JSON format. It generally happens when one has to transmit data over the network where Base64 encoding is well suited for encoding binary data.In this article, we will se
2 min read
How to Convert JSON to Blob in JavaScript ? This article explores how to convert a JavaScript Object Notation (JSON) object into a Blob object in JavaScript. Blobs represent raw data, similar to files, and can be useful for various tasks like downloading or processing JSON data. What is JSON and Blob?JSON (JavaScript Object Notation): A light
2 min read
How to convert blob to base64 encoding using JavaScript ? Blob in JavaScript is a fundamental data type representing bytes of data. It serves as the underlying structure for files and is supported by web browsers, capable of storing and retrieving data from memory. Blobs have specific sizes and file types like regular files and can be handled with Buffers,
2 min read
How to Convert Blob Data to JSON in JavaScript ? When dealing with Blob data in JavaScript, such as binary data or files, we may need to convert it into JSON format for doing so JavaScript provides us with various methods as listed below. Table of Content Using FileReader APIUsing TextDecoder APIUsing FileReader APIIn this approach, we first use t
2 min read
How to convert image into base64 string using JavaScript ? In this article, we will convert an image into a base64 string using Javascript. The below approaches show the methods to convert an image into a base64 string using Javascript.ApproachHere we will create a gfg.js file which will include JavaScript code and one gfg.html file.Now we will put onchange
2 min read
How to Convert JSON to ArrayBuffer in JavaScript? An ArrayBuffer is a complex data type, and structures which has a fixed length and takes binary content as the whole. Any variable that contains pure binary data will be defined in JavaScript as Simple Data, however on some occasions it is sometimes necessary to convert JSON data to an ArrayBuffer,
4 min read
Convert base64 String to ArrayBuffer In JavaScript A Base64 string represents binary data in an ASCII string format by translating it into a radix-64 representation. Often used to encode binary data in text-based formats like JSON or HTML, it needs to be converted back into its original binary format for further processing. An ArrayBuffer in JavaScr
2 min read
How to Upload Files in JavaScript? We upload files using JavaScript, for this we have to capture form elements, gather information from FormData for easier file uploads, intercept submission events, and utilize Fetch API for asynchronous server requests, for enhanced user experience and efficient data handling. ApproachProject Setup:
1 min read