1.使用
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec --> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.13</version> </dependency>
2.编码:
public static String encodeBase64File(String path){ ByteArrayOutputStream data = new ByteArrayOutputStream(); try { // 创建URL URL url = new URL(path); byte[] by = new byte[1024]; // 创建链接 HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setConnectTimeout(5000); int responseCode = con.getResponseCode(); log.info("responseCode:" + responseCode + "-------------- 图片url:" + con.getURL()); if (responseCode > 300 || responseCode < 200) { String[] s = path.split("/"); if (s.length - 1 >= 0) { String newUrl = "https://qimg.0easy.com/".concat(s[s.length - 1]); con.disconnect(); url = new URL(newUrl); con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(5000); con.setReadTimeout(30000); con.connect(); responseCode = con.getResponseCode(); } log.info("responseCode:" + responseCode + "-------------- 图片url:" + con.getURL()); if (responseCode > 300 || responseCode < 200) { con.disconnect(); return "图片信息获取失败"; } } InputStream is = con.getInputStream(); // 将内容放到内存中 int len = -1; while ((len = is.read(by)) != -1) { data.write(by, 0, len); } is.close(); } catch (IOException e) { e.printStackTrace(); } // 对字节数组Base64编码 // String header="data:image/jpg;base64,";//如果是在html中则加上 return Base64.encodeBase64String(data.toByteArray()); }
解码:
public static void toFile(String base64Code, String targetPath) throws Exception { byte[] buffer = Base64.decodeBase64(base64Code); FileOutputStream out = new FileOutputStream(targetPath); out.write(buffer); out.close(); }
同样的转pdf
byte[] bytes = FileUtils.readFileToByteArray(new File("c:\\z_test\\test1.pdf")); String s = Base64.encodeBase64String(bytes); System.out.println(s); byte[] buffer = Base64.decodeBase64(s); FileOutputStream out = new FileOutputStream("C:\\z_test\\2.pdf"); out.write(buffer); out.close();