java/Springboot项目把Base64数据转为文件

导读:本篇文章讲解 java/Springboot项目把Base64数据转为文件,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

前言

以下记录如何将base64的数据转为文件保存在本地

依赖

pom.xml需要导入以下依赖

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

base64转文件工具代码

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;

public class Base64ToFile {
    // 传入base64编码字符以及保存路径
    public String Base64ToFile(String base64, String filePath) throws IOException {
    // base64编码字符必须不能包含base64的前缀,否则会报错
    // filePath需要为具体到文件的名称和格式,如111.txt
    // 文件路径需要双斜杠转义,如:  D:\\files\\111.txt
        if (base64 == null && filePath == null) {
            return "生成文件失败,未传入参数!";
        }
        // 判断是否base64是否包含data:image/png;base64等前缀,如果有则去除
        if (base64.contains("data:image/png;base64")) {
            base64 = base64.substring(22);
            System.out.println("包含png"+base64);
        }
        if (base64.contains("data:image/jpeg;base64")) {
            base64 = base64.substring(23);
            System.out.println("包含jpeg"+base64);
        }
        if (base64.contains("data:application/pdf;base64")) {
            base64 = base64.substring(28);
            System.out.println("包含pdf"+base64);
        }
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] bytes = decoder.decodeBuffer(base64);
        for (int i = 0; i<bytes.length; ++i) {
            // 调整异常数据
            if (bytes[i] < 0) {
                bytes[i] +=256;
            }
        }
        OutputStream outputStream = null;
        InputStream inputStream = new ByteArrayInputStream(bytes);
        // 此处判断文件夹是否存在,不存在则创建除文件外的父级文件夹
        File file = new File(filePath);
        if (!file.exists()) {
            System.out.println("上级目录"+file.getParentFile());
            file.getParentFile().mkdirs();
        }
        try {
            // 生成指定格式文件
            outputStream = new FileOutputStream(filePath);
            byte[] buff = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buff)) != -1) {
                outputStream.write(buff, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            outputStream.flush();
            outputStream.close();
        }
        return "生成文件成功!";
    }
}

结语

以上为把Base64转文件的具体代码

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由半码博客整理,本文链接:https://www.bmabk.com/index.php/post/101157.html

(0)
小半的头像小半

相关推荐

半码博客——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!