Base64转MultipartFile工具类(转载,拿来即用)

该博客详细介绍了如何将Base64编码的数据转换为MultipartFile对象,提供了两种构造方法,一种处理带dataURI的base64数据,另一种处理不带dataURI的。文章还包含了一个使用示例,展示了如何创建并使用这个转换类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

话不多说,上码。

public class Base64ToMulti implements MultipartFile {
    //后缀
    private String suffix;
    //字节数组
    private byte[] content;
    //类型
    private String contentType;


    /**
     * 带dataURI的base64数据
     *
     * @param base64
     */
    public Base64ToMulti(String base64) {
        String[] data = base64.split(",");
        this.content = Base64.getDecoder().decode(data[1].getBytes());
        this.suffix = data[0].split(";")[0].split("/")[1];
        this.contentType = data[0].split(";")[0].split(":")[1];
    }

    /**
     * 不带dataURI的base64数据
     *
     * @param base64      base64数据
     * @param suffix      文件后缀名
     * @param contentType 内容类型
     */
    public Base64ToMulti(String base64, String suffix, String contentType) {
        this.content = Base64.getDecoder().decode(base64.getBytes());
        this.suffix = suffix;
        this.contentType = contentType;
    }

    @Override
    public String getName() {
        return "temp_" + System.currentTimeMillis();
    }

    @Override
    public String getOriginalFilename() {
        return "temp_" + System.currentTimeMillis() + "." + suffix;
    }

    @Override
    public String getContentType() {
        return contentType;
    }

    @Override
    public boolean isEmpty() {
        return content == null || content.length == 0;
    }

    @Override
    public long getSize() {
        return content.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return content;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(content);
    }

    @Override
    public void transferTo(File file) throws IOException, IllegalStateException {
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(content);
        }
    }


    public static MultipartFile getMultipartFile(String base64) {
        return new Base64ToMulti(base64);
    }

    public static MultipartFile getMultipartFile(String base64, String suffix, String contentType) {
        return new Base64ToMulti(base64, suffix, contentType);
    }
}

使用:

在这里插入图片描述

转载文章:

https://blog.csdn.net/ShuSheng0007/article/details/118230374

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值