public String fileToBase64(MultipartFile file) throws Exception {
String return_base64="";
File tmpFile = new File("/" + UUID.randomUUID()+ file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")));
file.transferTo(tmpFile);
if (!file.isEmpty()) {
if (file.getSize() > 51200) {
//大于50K进行压缩
Thumbnails.of(tmpFile).scale(0.1f).toFile(tmpFile);
}
byte[] data = new byte[1024];
FileInputStream fis = new FileInputStream(tmpFile);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
int n;
while ((n = fis.read(data)) != -1) {
bos.write(data, 0, n);
}
fis.close();
data = bos.toByteArray();
bos.close();
tmpFile.delete();
return_base64="data:" + file.getContentType() + ";base64," + Base64.getEncoder().encodeToString(data);
}
return return_base64;
}
Thumbnails.jar-下载地址:https://repo1.maven.org/maven2/net/coobird/thumbnailator/