#base64引入java
這裏使用的是mavenapp
<dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.10</version> </dependency>
#base64與String轉換maven
@RequestMapping(value="/base64TextTest") public static void base64TextTest() throws IOException { final Base64 base64 = new Base64(); final String text = "test"; final byte[] textByte = text.getBytes("UTF-8"); //編碼 final String encodedText = base64.encodeToString(textByte); System.out.println(encodedText); //解碼 System.out.println(new String(base64.decode(encodedText), "UTF-8")); }
#base64與文件轉換編碼
@RequestMapping(value="/base64FileTest") public static void base64FileTest() throws IOException { String base64String = null; InputStream in = null; final Base64 base64 = new Base64(); String fileName = "D:/data/20191217145156.png"; File file = new File(fileName); in = new FileInputStream(file); byte[] bytes=new byte[(int)file.length()]; in.read(bytes);
base64String = base64.encodeToString(bytes); System.out.println(base64String);
File file2 = null; //建立文件目錄 String filePath="D:/data1";
// String filePath=request.getSession().getServletContext().getRealPath("images/"); File dir=new File(filePath); if (!dir.exists() && !dir.isDirectory()) { dir.mkdirs(); } BufferedOutputStream bos = null; java.io.FileOutputStream fos = null; String fileName2 = "new_file.png"; try { byte[] bytes1 = Base64.decodeBase64(base64String); file=new File(filePath+"/"+fileName2); fos = new java.io.FileOutputStream(file); bos = new BufferedOutputStream(fos); bos.write(bytes1); } catch (Exception e) { e.printStackTrace(); } finally { if (bos != null) { try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } }