Java中如何实现文件与Base64之间互相转换呢?

欣喜 Java经验 发布时间:2025-01-27 10:58:26 阅读数:829 1
下文笔者讲述文件与Base64之间互相转换的方法及示例分享,如下所示

1、文件转Base64工具类

    可以将图片、视频转化为Base64格式

/**
 * 文件转Base64
 * @param filePath
 * @return
 */
public static String convertFileToBase64(String filePath) {
    try {
        // 读取文件为字节数组
        byte[] fileBytes = Files.readAllBytes(Paths.get(filePath));

        // 将字节数组转换为Base64编码的字符串
        String base64EncodedString = Base64.getEncoder().encodeToString(fileBytes);

        return base64EncodedString;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

2、Base64转文件工具类

    将Base64格式的图片、视频下载到本地

/**
 * Base64转文件
 * @param base64String Base64字符串
 * @param filePath 输出的文件路径
 * @param mimeType
 *  MIME类型:
 *      视频 video/mp4
 *      PNG: image/png
 *      JPEG: image/jpeg
 *      GIF: image/gif
 *      BMP: image/bmp
 *      WebP: image/webp
 * @return
 */
public static boolean convertBase64ToFile(String base64String, String filePath, String mimeType) {
    try {
        // 将Base64编码的字符串转换为字节数组
        byte[] fileBytes = Base64.getDecoder().decode(base64String);
        // 创建文件头信息
        String header = "data:" + mimeType + ";base64,";
        byte[] headerBytes = header.getBytes();
        // 合并文件头和文件内容
        byte[] combinedBytes = new byte[headerBytes.length + fileBytes.length];
        System.arraycopy(headerBytes, 0, combinedBytes, 0, headerBytes.length);
        System.arraycopy(fileBytes, 0, combinedBytes, headerBytes.length, fileBytes.length);
        // 将字节数组写入文件
        Files.write(Paths.get(filePath), fileBytes);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

"base64与文件" 互转示例大全

package org.ming;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

public class FileToBase64Converter {
    /**
     * 文件转Base64
     * @param filePath
     * @return
     */
    public static String convertFileToBase64(String filePath) {
        try {
            // 读取文件为字节数组
            byte[] fileBytes = Files.readAllBytes(Paths.get(filePath));

            // 将字节数组转换为Base64编码的字符串
            String base64EncodedString = Base64.getEncoder().encodeToString(fileBytes);

            return base64EncodedString;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 文件转Base64流程
     */
    public static list<Map<String, String>> fileToBase64() {
        List<Map<String, String>> dataList = new ArrayList<>();
        // 读取的图片路径
        String filePath = "D:\\test\\java265_test.png";
        // 读取的视频路径
        String videoPath = "D:\\test\\6666.mp4";

        String fileToBase64 = convertFileToBase64(filePath);
        String videoToBase64 = convertFileToBase64(videoPath);

        if (fileToBase64 != null) {
            System.out.println("图片转换成功");
            dataList.add(new HashMap<String, String>() {{
                put("outPath", String.format("D:\\test\\GcJcSbJkBjVo_%s.png", new Date().getTime()));
                put("base64Str", fileToBase64);
                put("mimeType", "image/png");
            }});
        } else {
            System.out.println("图片转换失败");
        }

        if (videoToBase64 != null) {
            System.out.println("视频转换成功");
            dataList.add(new HashMap<String, String>() {{
                put("outPath", String.format("D:\\test\\cs_%s.mp4", new Date().getTime()));
                put("base64Str", videoToBase64);
                put("mimeType", "video/mp4");
            }});
        } else {
            System.out.println("视频转换失败");
        }

        return dataList;
    }

    /**
     * Base64转文件
     * @param base64String Base64字符串
     * @param filePath 输出的文件路径
     * @param mimeType
     *  MIME类型:
     *      视频 video/mp4
     *      PNG: image/png
     *      JPEG: image/jpeg
     *      GIF: image/gif
     *      BMP: image/bmp
     *      WebP: image/webp
     * @return
     */
    public static boolean convertBase64ToFile(String base64String, String filePath, String mimeType) {
        try {
            // 将Base64编码的字符串转换为字节数组
            byte[] fileBytes = Base64.getDecoder().decode(base64String);
            // 创建文件头信息
            String header = "data:" + mimeType + ";base64,";
            byte[] headerBytes = header.getBytes();
            // 合并文件头和文件内容
            byte[] combinedBytes = new byte[headerBytes.length + fileBytes.length];
            System.arraycopy(headerBytes, 0, combinedBytes, 0, headerBytes.length);
            System.arraycopy(fileBytes, 0, combinedBytes, headerBytes.length, fileBytes.length);
            // 将字节数组写入文件
            Files.write(Paths.get(filePath), fileBytes);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * base64转文件流程
     * @param base64String
     * @param filePath
     */
    public static void base64ToFile(List<Map<String, String>> dataList) {
        for (Map<String, String> resMap : dataList) {
            boolean flag = convertBase64ToFile(resMap.get("base64Str"), resMap.get("outPath"), resMap.get("mimeType"));
            if (flag) {
                System.out.println(resMap.get("outPath") + " 转化成功");
            } else {
                System.out.println(resMap.get("outPath") + " 转化失败");
            }
        }
    }

    public static void main(String[] args) {
        // 文件转Base64
        List<Map<String, String>> dataList = fileToBase64();
        // Base64转文件
        base64ToFile(dataList);
    }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202501/17379467618252.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者