首先将 MultipartFile 文件转为byte[]数组形式,可以参考以下方法
private byte[] convertToByteArray(MultipartFile file) throws IOException {
InputStream inputStream = null;
try {
inputStream = file.getInputStream();
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes);
return bytes;
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
然后使用java.util自带的Base64工具即可转换
@Override
public String updateUserAvatar(MultipartFile file) {
//将file文件转为Base64
byte[] bytes = new byte[0];
try {
bytes = this.convertToByteArray(file);
} catch (IOException e) {
return "";
}
String avatar = Base64.getEncoder().encodeToString(bytes);
return avatar;
}