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}"/>

猜你喜欢

转载自www.cnblogs.com/qlqwjy/p/12121205.html