MultipartFile转base64
MultipartFile首先转换成file然后再讲file转换成base64格式
public String getBase64String(MultipartFile multiPartFile) throws IOException { String baseStr = null; //把MultipartFile转化为File File file = new File(multiPartFile.getOriginalFilename()); FileUtils.copyInputStreamToFile(multiPartFile.getInputStream(), file); try {
//file转base64 FileInputStream inputStream = new FileInputStream(file); byte[] buffer = new byte[(int) file.length()]; inputStream.read(buffer); inputStream.close(); baseStr = new BASE64Encoder().encode(buffer); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //删除临时文件 if (file.exists()) { file.delete(); } baseStr = baseStr.replaceAll("\r\n", ""); return baseStr; }
MultipartFile直接转base64
public String getBase64String(MultipartFile multiPartFile) throws IOException { String baseStr = null; BASE64Encoder encoder = new BASE64Encoder(); baseStr= encoder.encode(multiPartFile.getBytes()); baseStr = baseStr.replaceAll("\r\n", ""); return baseStr; }