如何对任意文件进行 Base64 编码
← 返回博客
如何对任意文件进行 Base64 编码
· 5 分钟阅读
文件 Base64 编码的应用场景
对文件进行 Base64 编码在以下场景中非常有用:通过 REST API(JSON 格式)传输二进制文件;将文件内容存储在 JSON 或 YAML 配置文件中;在 Kubernetes 的 Secret 资源中存储证书和密钥;将多个文件打包为单一文本格式传输;以及在不支持多部分表单上传的 API 中发送文件。
Base64 编码让任何文件(无论是 PDF、图片、音频、视频还是可执行程序)都能被当作纯文本字符串处理,这极大简化了跨系统数据交换的复杂性。
命令行工具编码文件
# Linux / macOS
# 编码文件并输出到屏幕 / Encode file and output to screen
base64 document.pdf
# 编码文件并保存到新文件 / Encode file and save to new file
base64 document.pdf > document.pdf.b64
# 不含换行符输出(适合 API 使用)/ Output without line breaks (for API use)
base64 -w 0 document.pdf > document.pdf.b64
# 解码 / Decode
base64 -d document.pdf.b64 > restored.pdf
# Windows PowerShell
[Convert]::ToBase64String([IO.File]::ReadAllBytes("document.pdf")) |
Out-File -Encoding ascii document.pdf.b64
# 解码 / Decode
$bytes = [Convert]::FromBase64String((Get-Content document.pdf.b64))
[IO.File]::WriteAllBytes("restored.pdf", $bytes)
Python 编码任意文件
import base64
import json
from pathlib import Path
def encode_file_to_base64(file_path):
"""读取文件并返回 Base64 字符串"""
with open(file_path, 'rb') as f:
return base64.b64encode(f.read()).decode('ascii')
def decode_base64_to_file(base64_str, output_path):
"""将 Base64 字符串解码并写入文件"""
data = base64.b64decode(base64_str)
with open(output_path, 'wb') as f:
f.write(data)
return len(data)
# 将文件嵌入 JSON / Embed file in JSON
def file_to_json_payload(file_path):
path = Path(file_path)
return {
"filename": path.name,
"size": path.stat().st_size,
"content": encode_file_to_base64(file_path)
}
payload = file_to_json_payload("report.pdf")
json_str = json.dumps(payload)
print(f"JSON payload size: {len(json_str)} chars")
Node.js 编码文件
const fs = require('fs');
const path = require('path');
// 同步方式 / Synchronous
function encodeFileSync(filePath) {
return fs.readFileSync(filePath).toString('base64');
}
// 异步方式(推荐用于生产)/ Async (recommended for production)
async function encodeFileAsync(filePath) {
const data = await fs.promises.readFile(filePath);
return data.toString('base64');
}
// 流式处理大型文件 / Stream large files
const { createReadStream } = require('fs');
const { Transform } = require('stream');
function encodeFileStream(inputPath, outputPath) {
const readStream = createReadStream(inputPath);
const writeStream = fs.createWriteStream(outputPath);
const base64Transform = new Transform({
transform(chunk, encoding, callback) {
callback(null, chunk.toString('base64'));
}
});
readStream.pipe(base64Transform).pipe(writeStream);
}
Kubernetes Secret 中的文件编码
Kubernetes 的 Secret 资源使用 Base64 存储敏感数据(如证书、密钥、配置文件)。Secret 的 YAML 文件中,data 字段下的每个值都必须是 Base64 编码的。注意:kubectl 工具的 create secret 命令会自动处理 Base64 编码,但手动编写 YAML 时需要自己编码。
# 生成 Kubernetes Secret 的 YAML
# Generate Kubernetes Secret YAML
CA_CERT=$(base64 -w 0 ca.crt)
TLS_KEY=$(base64 -w 0 server.key)
cat secret.yaml
apiVersion: v1
kind: Secret
metadata:
name: tls-secret
type: kubernetes.io/tls
data:
tls.crt: ${CA_CERT}
tls.key: ${TLS_KEY}
EOF
kubectl apply -f secret.yaml
处理大型文件的注意事项
对大型文件进行 Base64 编码时,需要特别注意内存使用。如果文件是 100MB,Base64 编码后约为 133MB,这在内存受限的环境中可能是个问题。对于超过几十 MB 的文件,建议使用流式处理(streaming),而不是将整个文件一次性读入内存。
另一个考量是传输效率。Base64 的 33% 体积开销在小文件上可以接受,但对于大型媒体文件,建议改用 multipart/form-data 格式直接上传二进制数据,这样没有体积开销,且大多数 Web 框架和云存储服务都原生支持。
验证编码结果的完整性
在将文件的 Base64 编码结果用于生产系统之前,建议验证其完整性:将 Base64 字符串解码,并与原始文件的哈希值(MD5 或 SHA-256)对比,确保数据没有在编码/解码过程中损坏。
import base64
import hashlib
def verify_base64_file(original_path, base64_str):
"""验证 Base64 字符串是否与原文件一致"""
# 计算原始文件的 SHA-256
with open(original_path, 'rb') as f:
original_hash = hashlib.sha256(f.read()).hexdigest()
# 解码 Base64 并计算哈希
decoded = base64.b64decode(base64_str)
decoded_hash = hashlib.sha256(decoded).hexdigest()
if original_hash == decoded_hash:
print("Integrity verified: hashes match")
return True
else:
print(f"MISMATCH! Original: {original_hash}, Decoded: {decoded_hash}")
return False
立即尝试在线工具,无需安装,免费使用。
打开工具 →
立即免费使用相关工具
免费使用 →