Base64转MultipartFile工具类

import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author Administrator
 */
public class Base64ToMultipartFile implements MultipartFile {
    private final byte[] fileContent;

    private final String extension;
    private final String contentType;

    private final String originalFilename;

    /**
     * @param base64
     * @param dataUri     格式类似于: data:image/png;base64
     */
    public Base64ToMultipartFile(String base64, String dataUri,String originalfilename) {
        this.fileContent = Base64.getDecoder().decode(base64.getBytes(StandardCharsets.UTF_8));
        this.extension = dataUri.split(";")[0].split("/")[1];
        this.contentType = dataUri.split(";")[0].split(":")[1];
        this.originalFilename = originalfilename;
    }
    @Override
    public String getName() {
        return "param_" + System.currentTimeMillis();
    }

    @Override
    public String getOriginalFilename() {
        //return "file_" + System.currentTimeMillis() + "." + extension;
        return originalFilename;
    }

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

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

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

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

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

    @Override
    public void transferTo(File file) throws IOException, IllegalStateException {
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(fileContent);
        }
    }
    
    public static void main(String [] args){
        String base64 = "";
        String originalfilename = "11.pdf";
        final String[] base64Array = base64.split(",");
        // base64转为流
        String dataUir = base64Array[0];
        String data = base64Array[1];
        MultipartFile multipartFile = new Base64ToMultipartFile(data, dataUir,originalfilename);
    }
}

你可能感兴趣的:(Java,java,开发语言)