文件与BASE64相互转换

Posted by dm on December 14, 2021

base64文件类型,前缀

import java.util.Arrays;

/** @Author dongm @Description: base64文件类型,前缀 @Date 2021/12/2 */
public enum Base64FileTypeEnum {
  // 文件类型
  BASE64_FILETYPE_DOC("doc", "data:application/msword;base64,"),
  BASE64_FILETYPE_DOCX(
      "docx",
      "data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,"),
  BASE64_FILETYPE_XLS("xls", "data:application/vnd.ms-excel;base64,"),
  BASE64_FILETYPE_XLSX(
      "xlsx", "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,"),
  BASE64_FILETYPE_PDF("pdf", "data:application/pdf;base64,"),
  BASE64_FILETYPE_PPT("ppt", "data:application/vnd.ms-powerpoint;base64,"),
  BASE64_FILETYPE_PPTX(
      "pptx",
      "data:application/vnd.openxmlformats-officedocument.presentationml.presentation;base64,"),
  BASE64_FILETYPE_TXT("txt", "data:text/plain;base64,"),

  // 图片类型
  BASE64_FILETYPE_PNG("png", "data:image/png;base64,"),
  BASE64_FILETYPE_JPG("jpg", "data:image/jpeg;base64,"),
  BASE64_FILETYPE_JPEG("jpeg", "data:image/jpeg;base64,"),
  BASE64_FILETYPE_GIF("gif", "data:image/gif;base64,"),
  BASE64_FILETYPE_SVG("svg", "data:image/svg+xml;base64,"),
  BASE64_FILETYPE_ICO("ico", "data:image/x-icon;base64,"),
  BASE64_FILETYPE_BMP("bmp", "data:image/bmp;base64,"),

  // 二进制流
  BASE64_FILETYPE_OCTET_STREAM("octet-stream", "data:application/octet-stream;base64,"),
  ;

  private String code;
  private String value;

  private Base64FileTypeEnum(String code, String value) {
    this.code = code;
    this.value = value;
  }

  public String getCode() {
    return code;
  }

  public String getValue() {
    return value;
  }

  public static String value(String code) {
    Base64FileTypeEnum[] types = values();
    return Arrays.stream(types)
        .filter(x -> x.getCode().equals(code))
        .findFirst()
        .map(Base64FileTypeEnum::getValue)
        .orElse(null);
  }
}

文件转换base64

import com.xcb.pay.enums.Base64FileTypeEnum;
import org.apache.commons.codec.binary.Base64;

import java.io.*;

/** @Author dongm @Description: @Date 2021/12/2 */
public class FileUtils {

  // 获取文件转换之后的base64内容
  public static String encodeBase64File(String prefix, File file) {
    try {
      if (file == null || !file.exists() || prefix == null) {
        return null;
      }
      long beginTime = System.currentTimeMillis();
      // base64文件前缀
      String base64Format = Base64FileTypeEnum.value(prefix.toLowerCase());
      if (base64Format == null || "".equals(base64Format)) {
        return null;
      }

      // 获取文件流
      InputStream in = new FileInputStream(file);
      BufferedInputStream bufInput = new BufferedInputStream(in); // 缓存流

      // 先把二进制流写入到ByteArrayOutputStream中
      ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
      byte[] bt = new byte[4096];
      int len;
      while ((len = bufInput.read(bt)) != -1) {
        byteArray.write(bt, 0, len);
      }
      byteArray.flush();

      long endTime = System.currentTimeMillis();
      System.out.println(
          "==>encodeBase64File, 把文件转换成base64编码, 总耗时: " + (endTime - beginTime) + "ms");

      // 返回
      return base64Format + Base64.encodeBase64String(byteArray.toByteArray());
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }

  // 把base64文件解码
  public static String decodeBase64String(String prefix, String base64String) {
    try {
      if (prefix == null || base64String == null) {
        return null;
      }
      long beginTime = System.currentTimeMillis();

      // 把base64前缀截取掉
      // base64文件前缀
      String value = Base64FileTypeEnum.value(prefix.toLowerCase());
      if (value == null || "".equals(value)) {
        return null;
      }
      // 替换
      String tempBase64String = base64String.replace(value, "");

      // 把base64字符串转换成字节
      byte[] bytes = Base64.decodeBase64(tempBase64String);

      // 转换成字节输入流
      ByteArrayInputStream in = new ByteArrayInputStream(bytes);

      // 把base64编码文件还原, 并存放到指定磁盘路径中
      OutputStream out =
          new FileOutputStream(
              new File("/var/folders/mv/ss9j08td0wx8rmzmcl77k6rc0000gn/T" + prefix));

      // 写文件
      byte[] buffer = new byte[4096];
      int len = 0;
      while ((len = in.read(buffer)) != -1) {
        out.write(buffer, 0, len); // 文件写操作
      }

      long endTime = System.currentTimeMillis();
      System.out.println(
          "==>decodeBase64String, 解析base64编码文件, 总耗时: " + (endTime - beginTime) + "ms");
      return "success";
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }

  /*public static void main(String[] args) {
    // 获取文件, 对文件base64编码
    File file = new File("D:\\test.txt");
    String prefix = "txt";

    // base64文件内容
    String base64String = FileUtils.encodeBase64File(prefix, file);
    System.out.println("文件base64加密之后的内容(太长, 控制台可能打印不出来): \n" + base64String);

    // 获取base64文件, 进行解码
    //		FileUtils.decodeBase64String(prefix, base64String);
  }*/
}