Base64 file uploads

How to encode files as Base 64 encoded strings in several languages

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)

Related content

Javascript email libraries for MailSlurp

Nodemailer alternatives to send and receieve email in code and tests

Send attachments with an Email API

How to send email attachments using MailSlurp API.

Email attachment size limit

Email MIME type message attachment file size limits and conventions

Fastest way to start a typescript project

Modern typescript tooling has come a long way. See how to setup a new project with TS-Node, TSC, and typeconfig.json.

Fetch error message javascript

Handle response exceptions with Fetch in Javascript

GraphQL API disposable email accounts

How to create real email addresses using GraphQL to send and receive emails in tests and frontend applications.

Ready to dive in?Start building email applications today.