Converting Files to Base64 Strings in Different Languages

Converting Files to Base64: Node.js, Java, and Golang Ways

  • Table of contents

Uploading files to APIs like MailSlurp's typically involves sending a file as a base64 encoded string to a server as the text/plain body of an HTTP POST request. Converting a file to a base64 string means reading a file into a byte array and then encoding the byte array into a string using base64 encoding.

Here are different ways to convert a file to base64 in several common languages.

Node JS

To convert a file to Base64 string in Node:

import fs from 'fs';
// convert file
const base64String = fs.readFileSync('path/to/file', 'base64');
// or convert a string
const fromString = new Buffer('file-content').toString('base64');

Java

To convert a file to Base64 string in Java 8+:

import java.util.Base64;
import java.nio.file.Files;

public String getFileAsBase64String(File file) {
    byte[] bytes= Files.readAllBytes(file.toPath());
    return Base64.getEncoder().encodeToString(bytes);
}

Golang

To convert a file to Base64 string in Golang:

package main

import (
    "bufio"
    "encoding/base64"
    "io/ioutil"
    "os"
)

func main() {
    f, _ := os.Open("path/to/file")
    reader := bufio.NewReader(f)
    content, _ := ioutil.ReadAll(reader)
    base64String := base64.StdEncoding.EncodeToString(content)