All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.nextpls.sdk.utils.BASE64DecodedMultipartFile Maven / Gradle / Ivy

The newest version!
package com.nextpls.sdk.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Base64;

/**
 * base64转MultipartFile
 */
public class BASE64DecodedMultipartFile implements MultipartFile {

    public static final String IMAGE_PREFIX = "data:image/jpeg;base64,";

    private final byte[] imgContent;
    private final String header;

    public BASE64DecodedMultipartFile(byte[] imgContent, String header) {
        this.imgContent = imgContent;
        this.header = header.split(";")[0];
    }

    @Override
    public String getName() {
        return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
    }

    @Override
    public String getOriginalFilename() {
        return System.currentTimeMillis() + (int) Math.random() * 10000 + "." + header.split("/")[1];
    }

    @Override
    public String getContentType() {
        return header.split(":")[1];
    }

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

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

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

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

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        new FileOutputStream(dest).write(imgContent);
    }

    /**
     * base64转MultipartFile文件
     *
     * @param base64 bsse64
     * @return MultipartFile
     */
    public static MultipartFile base64ToMultipart(String base64) {
        byte[] b = Base64.getDecoder().decode(base64);

        for (int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {
                b[i] += 256;
            }
        }

        return new BASE64DecodedMultipartFile(b, IMAGE_PREFIX);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy