How to convert byte array to MultipartFile

前端 未结 2 1620
余生分开走
余生分开走 2020-12-01 03:56

I am receiving image in the form of BASE64 encoded String(encodedBytes) and use following approach to decode into byte[] at server side.

BASE64Decoder decode         


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 04:15

    org.springframework.web.multipart.MultipartFile is an interface so firstly you are going to need to work with an implementation of this interface.

    The only implementation that I can see for that interface that you can use out-of-the-box is org.springframework.web.multipart.commons.CommonsMultipartFile. The API for that implementation can be found here

    Alternatively as org.springframework.web.multipart.MultipartFile is an interface, you could provide your own implementation and simply wrap your byte array. As a trivial example:

    /*
    *

    * Trivial implementation of the {@link MultipartFile} interface to wrap a byte[] decoded * from a BASE64 encoded String *

    */ public class BASE64DecodedMultipartFile implements MultipartFile { private final byte[] imgContent; public BASE64DecodedMultipartFile(byte[] imgContent) { this.imgContent = imgContent; } @Override public String getName() { // TODO - implementation depends on your requirements return null; } @Override public String getOriginalFilename() { // TODO - implementation depends on your requirements return null; } @Override public String getContentType() { // TODO - implementation depends on your requirements return null; } @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); } }

提交回复
热议问题