[Base64] 前端 base64 上传文件
前端
FileReader
将文件转换为 Base64 编码字符串,然后将其作为请求体发送到后端。
<input type="file" id="fileInput" />
<button onclick="uploadFileAsBase64()">上传文件</button>
<script>
function uploadFileAsBase64() {
const fileInput = document.getElementById("fileInput");
const file = fileInput.files[0];
if (file) {
const reader = new FileReader();
// 当文件读取完成时
reader.onload = function (event) {
// 获取 Base64 编码的字符串
const base64String = event.target.result.split(",")[1]; // 去掉前面的data:URL前缀
// 发送到后端
fetch("/upload", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
fileName: file.name,
fileType: file.type,
fileData: base64String,
}),
})
.then((response) => response.json())
.then((data) => {
console.log("上传成功:", data);
})
.catch((error) => {
console.error("上传失败:", error);
});
};
// 读取文件为 Data URL
reader.readAsDataURL(file);
} else {
alert("请选择文件");
}
}
</script>
后端
需要解析接收到的 Base64 字符串并将其解码回二进制数据,以保存文件或进行其他操作。
const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();
app.use(express.json({ limit: '10mb' })); // 增加限制以处理大文件
app.post('/upload', (req, res) => {
const { fileName, fileType, fileData } = req.body;
// 将 Base64 字符串解码为二进制数据
const base64Data = fileData.replace(/^data:image\/\w+;base64,/, ''); // 对于图片,移除 MIME 类型前缀
const buffer = Buffer.from(base64Data, 'base64');
// 将文件保存到磁盘
fs.writeFile(path.join(__dirname, 'uploads', fileName), buffer, (err) => {
if (err) {
console.error('保存文件时出错:', err);
return res.status(500).json({ status: 'error', message: '上传失败' });
}
res.json({ status: 'success', message: '文件上传成功' });
});
});
app.listen(3000, () => {
console.log('服务器正在监听端口 3000');
});
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
@RestController
public class FileUploadController {
@PostMapping("/upload")
public String uploadFile(@RequestBody FileUploadRequest request) {
try {
// 将 Base64 字符串解码为二进制数据
byte[] data = Base64.getDecoder().decode(request.getFileData());
// 将文件保存到磁盘
File file = new File("./uploads/" + request.getFileName());
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(data);
}
return "File uploaded successfully";
} catch (IOException e) {
e.printStackTrace();
return "File upload failed";
}
}
static class FileUploadRequest {
private String fileName;
private String fileData;
// Getters and setters
}
}