package com.bcxin.autodownloadupload.common.utils;

import cn.hutool.core.codec.Base64;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;

public class Base64Util {


    /**
     * description：文件转Base64
     * author：linchunpeng
     * date：2024/3/14
     */
    public static String fileToBase64(File file) {
        return Base64.encode(file);
    }

    /**
     * description：Base64转文件
     * author：linchunpeng
     * date：2024/3/14
     */
    public static File base64ToFile(String base64, String filePath) {
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        byte[] buffer;
        try {
            BASE64Decoder base64Decoder = new BASE64Decoder();
            buffer = base64Decoder.decodeBuffer(base64);
            FileOutputStream out = new FileOutputStream(filePath);
            out.write(buffer);
            out.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return file;
    }

}
