java对文件的二进制流base64编码解码


1.java对文件的二进制流base64编码解码

一般保存文件的时候选择的方式是将url存进数据库。今天遇到一个对接传文件流的二进制base64编码,简单记录一下。

 

依赖于commons-io包和commons-codec包。

 编码的方法如下:

    public static String encodeFile(File file) throws IOException {
        byte[] readFileToByteArray = FileUtils.readFileToByteArray(file);
        return Base64.encodeBase64String(readFileToByteArray);
    }

    public static String encodeFile(String filePath) throws IOException {
        return encodeFile(new File(filePath));
    }

 

解码的方法如下:(FileUtils会自动创建文件)

    public static void decodeFile(String codes, File file) throws IOException {
        byte[] decodeBase64 = Base64.decodeBase64(codes);
        FileUtils.writeByteArrayToFile(file, decodeBase64);
    }

    public static void decodeFile(String codes, String filePath) throws IOException {
        decodeFile(codes, new File(filePath));
    }

 

补充:有时候将图片进行base64编码之后存库可以用下面方式进行显示

<img src="data:image/jpeg;base64,${codes}"/>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM