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

 

相关文章:

  • 2021-12-06
  • 2021-11-17
  • 2021-06-20
  • 2022-01-27
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-08-08
  • 2022-12-23
  • 2022-01-22
  • 2022-12-23
  • 2022-12-23
  • 2021-04-26
相关资源
相似解决方案