How to convert byte array to MultipartFile

90,547

Solution 1

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:

/*
*<p>
* Trivial implementation of the {@link MultipartFile} interface to wrap a byte[] decoded
* from a BASE64 encoded String
*</p>
*/
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);
        }
    }

Solution 2

This answer has already been answered above. Recently i was working on the requirement to convert byte array object to multipartfile object. There are two ways to achieve this.

Approach 1:

Use the default CommonsMultipartFile where you to use the FileDiskItem object to create it. Example:

Approach 1:

Use the default CommonsMultipartFile where you to use the FileDiskItem object to create it. Example:

FileItem fileItem = new DiskFileItem("fileData", "application/pdf",true, outputFile.getName(), 100000000, new java.io.File(System.getProperty("java.io.tmpdir")));              
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);

Approach 2:

Create your own custom multipart file object and convert the byte array to multipartfile.

public class CustomMultipartFile implements MultipartFile {

private final byte[] fileContent;

private String fileName;

private String contentType;

private File file;

private String destPath = System.getProperty("java.io.tmpdir");

private FileOutputStream fileOutputStream;

public CustomMultipartFile(byte[] fileData, String name) {
    this.fileContent = fileData;
    this.fileName = name;
    file = new File(destPath + fileName);

}

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

public void clearOutStreams() throws IOException {
if (null != fileOutputStream) {
        fileOutputStream.flush();
        fileOutputStream.close();
        file.deleteOnExit();
    }
}

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

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

This how you can use above CustomMultipartFile object.

String fileName = "intermediate.pdf";
CustomMultipartFile customMultipartFile = new CustomMultipartFile(bytea, fileName);
try {
customMultipartFile.transferTo(customMultipartFile.getFile());

} catch (IllegalStateException e) {
    log.info("IllegalStateException : " + e);
} catch (IOException e) {
    log.info("IOException : " + e);
}

This will create the required PDF and store that into

java.io.tmpdir with the name intermediate.pdf

Thanks.

Share:
90,547
Shoaib Chikate
Author by

Shoaib Chikate

Expertise in Spring, Hibernate, Java, Servlets, JSP, jQuery, JavaScript, Android, Angular, Angular JS, CSS3, HTML5.

Updated on August 29, 2021

Comments

  • Shoaib Chikate
    Shoaib Chikate over 2 years

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

    BASE64Decoder decoder = new BASE64Decoder();
    byte[] decodedBytes = decoder.decodeBuffer(encodedBytes);
    

    Now i want to convert it into MultipartFile using this byte obtained above?

    Is there any way to convert byte[] to org.springframework.web.multipart.MultipartFile??

  • Shoaib Chikate
    Shoaib Chikate over 10 years
    Very good solution given by you.Hope this question and answer will be useful for many people
  • Ascalonian
    Ascalonian over 9 years
    In transferTo, should the FileOutputStream be closed after the writing?
  • mommcilo
    mommcilo about 8 years
    Great implementation. Small correction for isEmpty() method @Override public boolean isEmpty() { return imgContent == null || imgContent.length == 0; }
  • Rob Lockwood-Blake
    Rob Lockwood-Blake almost 8 years
    Seeing as this still appears to be useful for people, updated to reflect @mommcilo comment above.
  • Mohan
    Mohan over 7 years
    It works awesome!!! Added .close() to outstream in transferTo to avoid warning. @RobBlake
  • Tisha
    Tisha over 7 years
    I get this error - No serializer found for class java.io.ByteArrayInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: com.here.oat.model.output.MultiPartImage["inputStream"])
  • burcakulug
    burcakulug over 5 years
    in JDK7+, you can change the transferTo method like this for autoclose: @Override public void transferTo(File dest) throws IOException, IllegalStateException { try(OutputStream os = new FileOutputStream(dest)) { os.write(imgContent); } }
  • ABC123
    ABC123 almost 5 years
    In approach 1 which library are FileItem and DiskFileItem from?
  • user2968675
    user2968675 almost 5 years
    @Jim - commons-fileupload, recent gradle cfg: compile group: 'commons-fileupload', name: 'commons-fileupload', version: '1.4'
  • tomkri
    tomkri over 2 years
    except method transerTo which i insipred by CommonsMultipartFile#transferTo(File) it works prerfectly. Much easier than looking for any other implementation.