If you searched for "file to base64", this guide shows exactly how to encode files in common languages and send them to APIs without common payload or encoding errors.

## Quick answer: what is file-to-Base64 conversion?

File-to-Base64 conversion means reading raw file bytes and encoding them into a text string using Base64. This is useful when APIs expect JSON-safe string payloads instead of binary multipart uploads.

## When Base64 uploads make sense

Use Base64 when:

- API accepts Base64 in JSON bodies
- transport pipeline is text-only
- you need deterministic snapshot payloads in tests

Prefer binary multipart uploads when possible for very large files.

## Important tradeoff: Base64 increases payload size

Base64 adds roughly 33% overhead compared to raw binary.

Practical impact:

- higher request size
- higher memory usage
- slower transfer for large files

Set request size limits and reject oversized payloads early.

## Node.js: convert file to Base64

```js
import fs from "node:fs";

const base64String = fs.readFileSync("path/to/file.pdf", "base64");
console.log(base64String.slice(0, 80));
```

Async variant:

```js
import { readFile } from "node:fs/promises";

const bytes = await readFile("path/to/file.pdf");
const base64String = bytes.toString("base64");
```

## Python: convert file to Base64

```python
import base64

with open('path/to/file.pdf', 'rb') as f:
    base64_string = base64.b64encode(f.read()).decode('utf-8')

print(base64_string[:80])
```

## Java: convert file to Base64

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

byte[] bytes = Files.readAllBytes(Path.of("path/to/file.pdf"));
String base64String = Base64.getEncoder().encodeToString(bytes);
System.out.println(base64String.substring(0, 80));
```

## Go: convert file to Base64

```go
package main

import (
  "encoding/base64"
  "fmt"
  "os"
)

func main() {
  content, err := os.ReadFile("path/to/file.pdf")
  if err != nil {
    panic(err)
  }
  base64String := base64.StdEncoding.EncodeToString(content)
  fmt.Println(base64String[:80])
}
```

## C#: convert file to Base64

```csharp
using System;
using System.IO;

byte[] bytes = File.ReadAllBytes("path/to/file.pdf");
string base64String = Convert.ToBase64String(bytes);
Console.WriteLine(base64String.Substring(0, 80));
```

## Sending Base64 to an API

Typical JSON payload:

```json
{
  "fileName": "invoice.pdf",
  "contentType": "application/pdf",
  "base64Contents": "JVBERi0xLjQKJ..."
}
```

Best practices:

- include filename and MIME type metadata
- validate Base64 string server-side
- enforce max size before decode

## Decode and verify during debugging

When troubleshooting, decode the payload and compare byte hashes.

Node.js example:

```js
import fs from "node:fs";

const decoded = Buffer.from(base64String, "base64");
fs.writeFileSync("decoded-file.pdf", decoded);
```

## Common Base64 upload errors

### Invalid character / malformed Base64

Cause: unescaped characters, truncated strings, or incorrect URL encoding.

Fix: validate with strict decoder and reject bad payloads.

### API payload too large

Cause: Base64 expansion exceeds request limits.

Fix: compress, chunk, or switch to multipart upload flow.

### Wrong content type

Cause: mismatched MIME metadata and file bytes.

Fix: infer and validate server-side before processing.

### Memory spikes in workers

Cause: loading large files fully into memory.

Fix: stream where possible, set memory and size constraints.

## Production checklist

1. Validate file extension and MIME type
2. Enforce max file size (raw + encoded)
3. Validate Base64 syntax before decode
4. Decode in controlled memory limits
5. Scan and sanitize if files are user-supplied
6. Log request IDs and failure reasons

## Related MailSlurp guides

- [Email attachments API](/guides/email-attachments-api/)
- [Attachments guide](/guides/attachments/)
- [Send emails in code](/guides/sending-emails/)
- [Email API product](/product/email-address-api/)

## Production attachment workflow checklist

Base64 conversion is only one step. For stable attachment delivery:

1. Validate attachment behavior in an [email sandbox](/product/email-sandbox/) before real sends.
2. Add attachment assertions to [email integration testing](/product/email-integration-testing/) pipelines.
3. Track attachment delivery and failure events with [email webhooks](/guides/email-webhooks/).
4. Route retries and fallback logic through [email automation routing](/product/email-automation-routing/).
5. Run recurring [deliverability tests](/testing/email-deliverability-test/) for large-payload workflows.

This prevents payload regressions from becoming customer-visible email
failures.

## FAQ

### Is Base64 encryption?

No. Base64 is encoding, not encryption.

### Why does file-to-Base64 feel slower?

Because payload size increases and encode/decode adds CPU overhead.

### Should I always upload files as Base64?

No. Use it only when API design or transport constraints require it.

## Final take

Base64 is a practical interoperability format for API file uploads, but it has real size and performance tradeoffs. Build with strict validation and size controls from the start.
