How to convert CSV file to Base64 in Javascript?

Converting a CSV file to Base64 in a JavaScript environment, especially on the client side (e.g., within a web browser), involves a slightly different approach than in a server-side environment like Node.js. Here's how you can achieve this in a browser. If you're in search of a quick, no-code solution, I created a free online CSV to Base64 converter, efficiently catering to both coding and non-coding needs.

Reading the CSV File

In a web browser, reading a CSV file typically involves using an input type="file" element to allow the user to select the file. Once the file is selected, you can read its contents using the FileReader API.

HTML:

<input type="file" id="csvFileInput" accept=".csv">
<button onclick="convertToBase64()">Convert to Base64</button>

JavaScript:

function convertToBase64() {
    const fileInput = document.getElementById('csvFileInput');
    const file = fileInput.files[0];

    if (file) {
        const reader = new FileReader();

        reader.onload = function(event) {
            const csvContent = event.target.result;
            // Proceed to encode this content to Base64
            const encodedCsv = btoa(unescape(encodeURIComponent(csvContent)));
            // Now, encodedCsv contains the Base64 representation of the CSV content

            console.log(encodedCsv); // For demonstration: log the Base64 string to the console
            // You can also manipulate the DOM to display the result or send this string to a server
        };

        reader.readAsText(file); // Read the file content as text
    } else {
        console.log("No file selected!");
    }
}

Explanation:

  1. HTML Setup: An input element of type "file" allows the user to select a CSV file. A button triggers the conversion process.

  2. File Reading: When the user selects a file and clicks the "Convert to Base64" button, the convertToBase64 function is called. This function uses the FileReader API to asynchronously read the content of the selected file.

  3. Base64 Encoding: After reading the file, the FileReader's onload event is triggered, and its callback function is executed. Inside this function, the CSV content read from the file is first ensured to be in the correct URI component format using encodeURIComponent and then converted to Base64 using the btoa function. The btoa function is a built-in JavaScript function that encodes a string in Base64.

  4. Usage: The encoded Base64 string can be logged to the console, displayed on the webpage, or sent to a server as needed.

This method provides a way to read and encode files in the browser without sending the file data to a server, enhancing privacy and reducing server load.