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);
        }
    }
Answer from Rob Lockwood-Blake on Stack Overflow
Top answer
1 of 2
69

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);
        }
    }
2 of 2
13

This question 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:

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.

🌐
Baeldung
baeldung.com › home › java › java io › convert byte[] to multipartfile in java
Convert byte[] to MultipartFile in Java | Baeldung
August 15, 2024 - In this tutorial, we’ll take a look at how to convert a byte array to MultipartFile.
Discussions

Need help to convert the inputstream to multipartfile in java
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
2
4
March 23, 2021
java - Convert byte[] to MultipartFile - Stack Overflow
I want create a File Excel, convert this file to MultipartFile.class because I have test that read files MultipartFile, I created my file, but I don't know transform byte[] to MultipartFile because... More on stackoverflow.com
🌐 stackoverflow.com
attachment - Java : InputStream to Multi-part file conversion, result file is empty - Stack Overflow
I am working on a Java application in which I am trying to create a Multipart file out of downloaded InputStream. Unfortunately, it is not working and the Multipart file is empty. I checked the siz... More on stackoverflow.com
🌐 stackoverflow.com
How to send ByteArrayInputStream in MultipartFile
If you are making an outgoing request from your spring boot app you can do it like so https://gist.github.com/BigMikeCodes/40c9cdfeee713a54246d3900af209b4d You will need to change the content type + filename + field name accordingly More on reddit.com
🌐 r/SpringBoot
6
11
January 14, 2025
🌐
Cacher
snippets.cacher.io › snippet › b641af03ef66ee4ce13e
convert byte data to MultipartFile in Spring MVC - Cacher Snippet
April 25, 2018 - import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.web.multipart.MultipartFile; public class BASE64DecodedMultipartFile implements MultipartFile { protected static final Logger log = LogManager.getLogger(BASE64DecodedMultipartFile.class); private byte[] imgContent; private String fileName; private String ext; public String getExt() { return ext; } @Override public String getName() { return
🌐
GitHub
gist.github.com › luanvuhlu › 9d833a832e7ffc2efb13775139d233b3
convert byte data to MultipartFile in Spring MVC · GitHub
convert byte data to MultipartFile in Spring MVC · Raw · BASE64DecodedMultipartFile.java · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Reddit
reddit.com › r/javahelp › need help to convert the inputstream to multipartfile in java
r/javahelp on Reddit: Need help to convert the inputstream to multipartfile in java
March 23, 2021 -

private MultipartFile getResize(MultipartFile orginalFile, int h, int w) throws IOException {

    File convFile = new File(orginalFile.getOriginalFilename());
    BufferedImage bImage = ImageIO.read(convFile);
    Image tmp = bImage.getScaledInstance(w, h, Image.SCALE_SMOOTH);
    BufferedImage resized = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = resized.createGraphics();
    g2d.drawImage(tmp, 0, 0, null);
    g2d.dispose();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ImageIO.write(resized, “png”, os);
    InputStream is = new ByteArrayInputStream(os.toByteArray());
    byte[] buffer = new byte[is.available()];

I am not able to figure out to return the multipartfile conversion for this image resize.

Top answer
1 of 2
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
2 of 2
1
Why would you want the conversion to be a MultipartFile? The only purpose of MultipartFile is to allow you to see the files contained in a multipart body request. The converted file you just created is not inside a multipart, so, what would be the point of having it as a MultipartFile?
🌐
YouTube
youtube.com › vlogize
How to Convert InputStream and Byte Array to MultipartFile in Java - YouTube
Disclaimer/Disclosure: Some of the content was synthetically produced using various Generative AI (artificial intelligence) tools; so, there may be inaccurac...
Published   July 5, 2024
Views   35
🌐
YouTube
youtube.com › hey delphi
Array : How to convert byte array to MultipartFile - YouTube
Array : How to convert byte array to MultipartFileTo Access My Live Chat Page, On Google, Search for "hows tech developer connect"I promised to reveal a secr...
Published   May 1, 2023
Views   1K
Find elsewhere
🌐
Twitter
twitter.com › baeldung › status › 1652258944377651204
New Post: Convert byte[] to MultipartFile in Java
April 29, 2023 - JavaScript is not available · We’ve detected that JavaScript is disabled in this browser. Please enable JavaScript or switch to a supported browser to continue using twitter.com. You can see a list of supported browsers in our Help Center · Help Center · Terms of Service Privacy Policy ...
🌐
Medium
medium.com › @javawithabhishek › how-to-convert-input-stream-to-multipartfile-using-java-07ce4c01834d
How to convert Input Stream to MultipartFile using Java | by Abhishek Sharma | Medium
August 31, 2025 - public class SimpleMultipartFileUtil { public static class SimpleMultipartFile implements MultipartFile { private final byte[] content; private final String originalFilename; private final String contentType; public SimpleMultipartFile(InputStream inputStream, String filename, String contentType) throws IOException { this.content = inputStream.readAllBytes(); this.originalFilename = filename; this.contentType = contentType; } @Override public String getName() { return "file"; } @Override public String getOriginalFilename() { return originalFilename; } @Override public String getContentType() {
🌐
Spring
docs.spring.io › spring-framework › docs › 5.0.8.RELEASE_to_5.1.0.RC1 › Spring Framework 5.1.0.RC1 › org › springframework › web › multipart › MultipartFile.html
MultipartFile
Return an InputStream to read the contents of the file from. The user is responsible for closing the returned stream. ... Return a Resource representation of this MultipartFile.
Top answer
1 of 1
4

The DiskFileItem uses a DeferredFileOutputStream which uses an in-memory byte-array that is only filled when bytes are actually transferred. Since files are used directly and no bytes are actually copied, the byte-array is never filled. See for yourself in the source code:
Source code CommonsMultipartFile
Source code DiskFileItem
Source code DeferredFileOutputStream

So, instead of just calling fileItem.getOutputStream();, transfer the bytes to fill the in-memory byte-array:

try (OutputStream out = fileItem.getOutputStream();
        InputStream in = Files.newInputStream(file.toPath())) {
    IOUtils.copy(in, dfos);
}

and then the tranferTo call will work.
This appears to be a bit cumbersome for just moving a file: CommonsMultipartFile only calls fileItem.write((File)dest) in the transferTo method. Below are two test cases, one using the DiskFileItem and one using the LocalFileItem. The code for LocalFileItem is shown further below.
I used dependencies org.springframework:spring-web:4.2.2.RELEASE, commons-fileupload:commons-fileupload:1.3.1 and junit:junit:4.12
Test class CommonMp:

import static org.junit.Assert.*;
import java.io.*;
import java.nio.charset.*;
import java.nio.file.*;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

public class CommonMp {

    private final Charset CS = StandardCharsets.UTF_8;

    @Test
    public void testLocalMp() {

        Path testInputFile = null, testOutputFile = null;
        try {
            testInputFile = prepareInputFile();
            LocalFileItem lfi = new LocalFileItem(testInputFile);
            CommonsMultipartFile cmf = new CommonsMultipartFile(lfi);
            System.out.println("Empty: " + cmf.isEmpty());
            testOutputFile = testInputFile.getParent().resolve("testMpOutput.txt");
            cmf.transferTo(testOutputFile.toFile());
            System.out.println("Size: " + cmf.getSize());
            printOutput(testOutputFile);
        } catch (Exception e) {
            e.printStackTrace();
            fail();
        } finally {
            deleteSilent(testInputFile, testOutputFile);
        }
    }

    @Test
    public void testMp() {

        Path testInputFile = null, testOutputFile = null;
        try {
            testInputFile = prepareInputFile();
            DiskFileItem di = new DiskFileItem("file", "text/plain", false, testInputFile.getFileName().toString(), 
                    (int) Files.size(testInputFile), testInputFile.getParent().toFile());
            try (OutputStream out = di.getOutputStream();
                    InputStream in = Files.newInputStream(testInputFile)) {
                IOUtils.copy(in, out);
            }
            CommonsMultipartFile cmf = new CommonsMultipartFile(di);
            System.out.println("Size: " + cmf.getSize());
            testOutputFile = testInputFile.getParent().resolve("testMpOutput.txt");
            cmf.transferTo(testOutputFile.toFile());
            printOutput(testOutputFile);
        } catch (Exception e) {
            e.printStackTrace();
            fail();
        } finally {
            deleteSilent(testInputFile, testOutputFile);
        }
    }

    private Path prepareInputFile() throws IOException {

        Path tmpDir = Paths.get(System.getProperty("java.io.tmpdir"));
        Path testInputFile = tmpDir.resolve("testMpinput.txt");
        try (OutputStream out = Files.newOutputStream(testInputFile)){
            out.write("Just a test.".getBytes(CS));
        }
        return testInputFile;
    }

    private void printOutput(Path p) throws IOException {

        byte[] outBytes = Files.readAllBytes(p);
        System.out.println("Output: " + new String(outBytes, CS));
    }

    private void deleteSilent(Path... paths) {

        for (Path p : paths) {
            try { if (p != null) p.toFile().delete(); } catch (Exception ignored) {}
        }
    }

}

The custom LocalFileItem class, YMMV!

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemHeaders;

public class LocalFileItem implements FileItem {

    private static final long serialVersionUID = 2467880290855097332L;

    private final Path localFile;

    public LocalFileItem(Path localFile) {
        this.localFile = localFile;
    }

    @Override
    public void write(File file) throws Exception {
        Files.move(localFile, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
    }

    @Override
    public long getSize() {

        // Spring's CommonsMultipartFile caches the file size and uses it to determine availability.
        long size = -1L;
        try {
            size = Files.size(localFile);
        } catch (IOException ignored) {}
        return size;
    }

    @Override
    public void delete() {
        localFile.toFile().delete();
    }

    /* *** properties and unsupported methods *** */

    private FileItemHeaders headers;
    private String contentType;
    private String fieldName;
    private boolean formField;

    @Override
    public FileItemHeaders getHeaders() {
        return headers;
    }

    @Override
    public void setHeaders(FileItemHeaders headers) {
        this.headers = headers;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        throw new IOException("Only method write(File) is supported.");
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

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

    @Override
    public String getName() {
        return localFile.getFileName().toString();
    }

    @Override
    public boolean isInMemory() {
        return false;
    }

    @Override
    public byte[] get() {
        throw new RuntimeException("Only method write(File) is supported.");
    }

    @Override
    public String getString(String encoding)
            throws UnsupportedEncodingException {
        throw new RuntimeException("Only method write(File) is supported.");
    }

    @Override
    public String getString() {
        throw new RuntimeException("Only method write(File) is supported.");
    }

    @Override
    public String getFieldName() {
        return fieldName;
    }

    @Override
    public void setFieldName(String name) {
        this.fieldName = name;
    }

    @Override
    public boolean isFormField() {
        return formField;
    }

    @Override
    public void setFormField(boolean state) {
        this.formField = state;
    }

    @Override
    public OutputStream getOutputStream() throws IOException {
        throw new IOException("Only method write(File) is supported.");
    }

}
🌐
Tabnine
tabnine.com › home page › code › java › org.springframework.web.multipart.multipartfile
org.springframework.web.multipart.MultipartFile.getBytes java code examples | Tabnine
@PostMapping("/upload") // //new annotation since 4.3 public String singleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) { if (file.isEmpty()) { redirectAttributes.addFlashAttribute("message", "Please select a file to upload"); return "redirect:uploadStatus"; } try { // Get the file and save it somewhere byte[] bytes = file.getBytes(); Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename()); Files.write(path, bytes); redirectAttributes.addFlashAttribute("message", "You successfully uploaded '" + file.getOriginalFilename() + "'"); } catch (IOException e) { e.printStackTrace(); } return "redirect:/uploadStatus"; }
🌐
LinkedIn
linkedin.com › posts › eugenparaschiv_convert-byte-to-multipartfile-in-java-activity-7061415824250609664-rjos
Eugen Paraschiv on LinkedIn: Convert byte[] to MultipartFile in Java | Baeldung
May 8, 2023 - New Post: Convert byte[] to MultipartFile in Java · 4 · Like · Comment · Share · Copy · LinkedIn · Facebook · Twitter · To view or add a comment, sign in · Eugen Paraschiv · Architect. Teaching Spring through video. 2h · Report this post · New Post: Message Acknowledgement in Spring Cloud AWS SQS v3 ·
🌐
Morioh
morioh.com › p › 5e3a3ac598ca
How to Convert a Spring MultipartFile to a File
morioh.com is your first and best source for all of the information you’re looking for. From general topics to more of what you would expect to find here, morioh.com has it all. We hope you find what you are searching for!
🌐
GitHub
github.com › OpenFeign › feign-form › blob › master › feign-form-spring › src › main › java › feign › form › spring › converter › ByteArrayMultipartFile.java
feign-form/feign-form-spring/src/main/java/feign/form/spring/converter/ByteArrayMultipartFile.java at master · OpenFeign/feign-form
December 31, 2024 - import java.io.InputStream; · import lombok.NonNull; import lombok.Value; import lombok.val; import org.springframework.web.multipart.MultipartFile; · /** * Straight-forward implementation of interface {@link MultipartFile} where the file · * data is held as a byte array in memory.
Author   OpenFeign
🌐
Electro4u
electro4u.net › blog › convert-byte-to-multipartfile-in-java-1319
Convert Byte[] to MultipartFile in Java with electro4u.net
import org.springframework.mock.web.MockMultipartFile; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; public class ByteToMultipartFileConverter { public static MultipartFile convert(byte[] bytes, String fileName) throws IOException { // Assuming bytes is your byte[] array // Create a MockMultipartFile MultipartFile multipartFile = new MockMultipartFile( fileName, // Original file name fileName, // Desired file name "application/octet-stream", // Content type bytes // Byte[] array ); return multipartFile; } public static void main(String[] args) throws IOException { byte[] byteData = { /* Your byte data here */ }; String fileName = "example.txt"; MultipartFile multipartFile = convert(byteData, fileName); // Now you can use the multipartFile object in your code } }
🌐
Javathinking
javathinking.com › blog › convert-bytes-to-multipartfile-java
Convert Bytes to MultipartFile in Java | JavaThinking.com
July 19, 2025 - Converting bytes to a MultipartFile in Java is a useful technique when dealing with file uploads and binary data. By creating a custom implementation of the MultipartFile interface, you can easily convert byte arrays to MultipartFile objects.