package com.common.core.utils; import org.springframework.web.multipart.MultipartFile; import sun.misc.BASE64Decoder; import java.io.*; /** * @Author holfeng * @Date 15:21 10/02/2022 * @Version 1.0 **/ public class BASE64DecodedMultipartFile implements MultipartFile { private byte[] fileContent; private String header; public BASE64DecodedMultipartFile(byte[] fileContent, String header) { this.fileContent = fileContent; this.header = header.split(";")[0]; } @Override public String getName() { return header.split("/")[1]; } @Override public String getOriginalFilename() { return header.split("/")[1]; } @Override public String getContentType() { return header.split(":")[1]; } @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 InputStream getInputStream() throws IOException { return new ByteArrayInputStream(fileContent); } @Override public void transferTo(File dest) throws IOException, IllegalStateException { FileOutputStream stream=null; try { stream = new FileOutputStream(dest); stream.write(fileContent); }catch (Exception e){ throw e; }finally { if(stream!=null)stream.close(); } } public static MultipartFile base64ToMultipart(String base64) throws IOException { String[] baseStrs = base64.split(","); BASE64Decoder decoder = new BASE64Decoder(); byte[] b = new byte[0]; b = decoder.decodeBuffer(baseStrs[1]); for (int i = 0; i < b.length; ++i) { if (b[i] < 0) { b[i] += 256; } } return new BASE64DecodedMultipartFile(b, baseStrs[0]); } }