java将文件转为base64字符串和将base64字符串转为文件

一、引入依赖

<dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.11</version>
        </dependency>

二、将文件转为base64字符串

AttachFile attachFile = fileList.get(0);
            File file = new File(shareFile + "/" + attachFile.getUploadPath() + "/" + attachFile.getCompressedName());
            if (file.exists()) {
                try (InputStream in = new FileInputStream(file)) {
                    byte[] data = new byte[in.available()];
                    in.read(data);
                    String url = "data:image/jpeg;base64," + Base64.encodeBase64String(data);
                    tempEntity2.setContent(url);
                    lt.add(tempEntity2);
                } catch (Exception e) {
                    logger.error("exception", e);
                }
            }

data:image/jpeg;base64,base64编码的jpeg图片数据,其中:data:image/jpg; 声明数据协议及类型名称,base64,编码形式为base64

三、将base64字符串转为文件

public static void base64ToFile(String base64Str, String targetFilePath) {
        byte[] buffer = Base64.decodeBase64(base64Str);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(targetFilePath);
            out.write(buffer);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

四、案例:将文件转为base64字符串,再转为文件

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.codec.binary.Base64;

public class Test {
    /**
     * @Description: 文件转为base64字符串。filePath:文件路径
     * @Param: [filePath]
     * @return: java.lang.String
     * @Date: 2020/12/25
     */
    public static String fileToBase64(String filePath) throws IOException {
        File file = new File(filePath);
        FileInputStream inputFile = null;
        byte[] buffer = null;
        try {
            inputFile = new FileInputStream(file);
            buffer = new byte[(int) file.length()];
            inputFile.read(buffer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != inputFile) {
                inputFile.close();
            }
        }
        byte[] bs = Base64.encodeBase64(buffer);
        return new String(bs);
    }

    /**
     * base64字符串转文件
     * @param base64Str
     * @param targetFilePath
     * @return
     */
    public static void base64ToFile(String base64Str, String targetFilePath) {
        byte[] buffer = Base64.decodeBase64(base64Str);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(targetFilePath);
            out.write(buffer);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        String filePath = "D:/upload/20211013/13e74a23-a901-4c66-ad52-84ef510d43a0.jpg";
        String base64Str = "";
        try {
            base64Str = fileToBase64(filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(base64Str);
        String targetFilePath = "C:/Users/miracle/Desktop/lujingshan.jpg";
        base64ToFile(base64Str, targetFilePath);
    }
}