Java base64 添加data URI
任何语言生成的base64均不会携带data URI,而前端在读取base64时需要携带data URI头
1 public String getContentType(Path path){ 2 try { 3 return Files.probeContentType(path); 4 } catch (IOException e) { 5 e.printStackTrace(); 6 } 7 return null; 8 } 9 10 public String getContentType(byte[] bytes){ 11 MagicMatch match = null; 12 try { 13 match = Magic.getMagicMatch(bytes); 14 } catch (MagicParseException e) { 15 e.printStackTrace(); 16 } catch (MagicMatchNotFoundException e) { 17 e.printStackTrace(); 18 } catch (MagicException e) { 19 e.printStackTrace(); 20 } 21 return match.getMimeType(); 22 } 23 24 public String encryptToBase64(String filePath) { 25 if (filePath == null) { 26 return null; 27 } 28 try { 29 Path path = Paths.get(filePath); 30 if(Files.exists(path,new LinkOption[]{ LinkOption.NOFOLLOW_LINKS})){ 31 byte[] b = Files.readAllBytes(path); 32 String contentType = getContentType(path); 33 String contentType1 = getContentType(b); 34 String base64str1 = DatatypeConverter.printBase64Binary(b); //Java7 35 String base64Str = Base64.getEncoder().encodeToString(b); 36 // cretate "data URI" 37 StringBuilder sb = new StringBuilder(); 38 sb.append("data:"); 39 sb.append(contentType); 40 sb.append(";base64,"); 41 sb.append(base64Str); 42 return sb.toString(); 43 } 44 return null; 45 } catch (IOException e) { 46 e.printStackTrace(); 47 } 48 return null; 49 }