java hutool MultipartFile转base64
时间: 2025-01-18 22:55:29 浏览: 51
将 MultipartFile
转换为 Base64 编码字符串
为了将 Spring Boot 中的 MultipartFile
对象转换成 base64 字符串,可以利用 Hutool 库来简化操作。Hutool 是一个 Java 工具包,提供了许多便捷的功能方法。
下面展示了一个具体实例:
添加依赖项
首先,在项目的 pom.xml 文件里加入 Hutool 的 Maven 依赖[^1]:
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.11</version>
</dependency>
实现 MultipartFile 到 Base64 的转换
接着编写一段用于处理文件上传并将文件内容编码为 base64 格式的控制器逻辑代码:
import cn.hutool.core.codec.Base64;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@RestController
public class FileController {
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) {
try {
byte[] bytes = file.getBytes();
// 使用 hutool 进行 base64 编码
String encodedString = Base64.encode(bytes);
return "Base64 Encoded string is " + encodedString;
} catch (IOException e) {
e.printStackTrace();
return "Failed to encode the uploaded file.";
}
}
}
这段程序接收来自客户端的一个或多個文件作为输入参数,并将其读取为字节数组形式;之后借助于 Hutool 提供的方法完成 base64 编码过程,最后返回给前端相应的结果信息。
相关推荐


















