3种方式
//第一种单图片转
@RequestMapping("/baseImage")
@ResponseBody
public String test(@RequestPart("file") MultipartFile file) throws Exception {
BASE64Encoder base64Encoder = new BASE64Encoder();
String base64EncoderImg = file.getOriginalFilename() + "," + base64Encoder.encode(file.getBytes());
return base64EncoderImg;
}
//第二种单图片转
/**
* 将MultipartFile 图片文件编码为base64
* @param file
* @return
* @throws Exception
*/
@RequestMapping("/baseImage2")
@ResponseBody
public String test2(@RequestPart("file") MultipartFile file) {
if (file == null || file.isEmpty()) {
throw new RuntimeException("图片不能为空!");
}
String fileName = file.getOriginalFilename();
String fileType = fileName.substring(fileName.lastIndexOf("."));
String contentType = file.getContentType();
byte[] imageBytes = null;
String base64EncoderImg = "";
try {
imageBytes = file.getBytes();
BASE64Encoder base64Encoder = new BASE64Encoder();
base64EncoderImg = "data:" + contentType + ";base64," + base64Encoder.encode(imageBytes);
base64EncoderImg = base64EncoderImg.replaceAll("[\\s*\t\n\r]", "");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return base64EncoderImg;
}
//第三种多图片上传转成多个base64字符串
/**
* 将MultipartFile[] 图片文件编码为base64
* @param files
* @return
* @throws Exception
*/
@RequestMapping("/baseImage3")
@ResponseBody
public List<String> test3(@RequestPart("file") MultipartFile[] files) {
if (files == null || files.length==0) {
throw new RuntimeException("图片不能为空!");
}
List<String> base64Imgs = new ArrayList<String>();
//判断file数组不能为空并且长度大于0
if (files != null && files.length > 0) {
//循环获取file数组中得文件
for (int i = 0; i < files.length; i++) {
MultipartFile file = files[i];
//单个一个一个图片转换成base64
if (!file.isEmpty()) {
String fileName = file.getOriginalFilename();
String fileType = fileName.substring(fileName.lastIndexOf("."));
String contentType = file.getContentType();
byte[] imageBytes = null;
String base64EncoderImg = "";
try {
imageBytes = file.getBytes();
BASE64Encoder base64Encoder = new BASE64Encoder();
base64EncoderImg = "data:" + contentType + ";base64," + base64Encoder.encode(imageBytes);
base64EncoderImg = base64EncoderImg.replaceAll("[\\s*\t\n\r]", "");
base64Imgs.add(base64EncoderImg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
return base64Imgs;
}