MockMultipartFile exists for this purpose. As in your snippet if the file path is known, the below code works for me.

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.mock.web.MockMultipartFile;

Path path = Paths.get("/path/to/the/file.txt");
String name = "file.txt";
String originalFileName = "file.txt";
String contentType = "text/plain";
byte[] content = null;
try {
    content = Files.readAllBytes(path);
} catch (final IOException e) {
}
MultipartFile result = new MockMultipartFile(name,
                     originalFileName, contentType, content);
Answer from Arun on Stack Overflow
🌐
javathinking
javathinking.com › blog › convert-file-to-multipartfile-java-spring-boot
Convert File to MultipartFile in Java Spring Boot — javathinking.com
Converting a File to a MultipartFile in a Java Spring Boot application can be easily achieved using the MockMultipartFile class. This conversion is useful in various scenarios such as unit testing, batch processing, and integrating with third-party ...
Discussions

Java spring: best way to convert a File to a MultipartFile - Stack Overflow
I created a file (below) but I want to convert it to MultipartFile, how can I do it? I already tried this code, without sucess: File file = new File("text.txt"); FileInputStream input = new More on stackoverflow.com
🌐 stackoverflow.com
java - Converting File to MultiPartFile with spring - Stack Overflow
I want to convert File to multipartfile with spring. I have make this: File in; MultipartFile file = null; in = new File("C:...file on disk"); int size = (int) in.length(); DiskFileItem fileItem = new DiskFileItem("file", "application/vnd.ms-excel", false, nomefile, size ,in.getAbsoluteFile()); file = new CommonsMultipartFile(fileItem); ... threw exception [Request processing failed; nested exception is java... More on stackoverflow.com
🌐 stackoverflow.com
April 20, 2017
Best way to convert Inputstream to Multipartfile
Data Brokers don't stand a chance because I mass delete all of my content using Redact - No AI training on my data, thank you very much. fuel shelter arrest mountainous cats boat divide stocking different humor More on reddit.com
🌐 r/SpringBoot
7
10
December 18, 2024
spring mvc - How to convert byte array to MultipartFile - Stack Overflow
12 How to solve the error "No serializer found for class java.io.ByteArrayInputStream " when passing MultipartFile using RestTemplate? 7 How to create MultipartFile object from InputStream in Spring Boot More on stackoverflow.com
🌐 stackoverflow.com
🌐
Baeldung
baeldung.com › home › spring › spring web › converting a spring multipartfile to a file
Converting a Spring MultipartFile to a File | Baeldung
October 23, 2025 - If you are using Spring Boot 2, you can use the Apache Commons IO and Apache Commons FileUpload libraries that provide APIs to convert File to MultipartFile.
🌐
Tabnine
tabnine.com › home › code library
Code Library - Tabnine
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
🌐
Baeldung
baeldung.com › home › spring › spring web › convert byte[] to multipartfile in java
Convert byte[] to MultipartFile in Java | Baeldung
August 15, 2024 - How to convert a byte array into a class which implements the Spring MultiPartFile interface.
Find elsewhere
🌐
Medium
medium.com › techpanel › multipartfile-with-springboot-d4901ee3e77d
MultipartFile with SpringBoot. This article explains two use cases of… | by Aakash Sorathiya | TechPanel | Medium
July 22, 2023 - Now, we will write a service class method that processes the request input and saves the file. public void uploadFile(MultipartFile file) throws UserException { try { if(file.isEmpty()) { throw new UserException("Empty file"); } Path destination = Paths.get("rootDir").resolve(file.getOriginalFilename()).normalize().toAbsolutePath(); Files.copy(file.getInputStream(), destiation); } catch(IOException e) { throw new UserException("Store exception"); } }
🌐
Spring
docs.spring.io › spring-framework › docs › 3.0.6.RELEASE_to_3.1.0.BUILD-SNAPSHOT › 3.1.0.BUILD-SNAPSHOT › org › springframework › web › multipart › MultipartFile.html
org.springframework.web.multipart Interface MultipartFile
If the file has been moved in the filesystem, this operation cannot be invoked again. Therefore, call this method just once to be able to work with any storage mechanism. ... java.lang.IllegalStateException - if the file has already been moved in the filesystem and is not available anymore for another transfer
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.

🌐
Reddit
reddit.com › r/javahelp › best way to convert a file to a multipartfile?
r/javahelp on Reddit: Best way to convert a File to a MultiPartFile?
October 27, 2022 -

Hi!

I am trying to convert a string that is a URL from a PDF to a File, and then that file to a MultiPartFile.

This is the code I am using to create the MultiPartFile.

File file = new File(fileName);
try (final FileInputStream input = new FileInputStream(file)) {
multipartFile = new MockMultipartFile(
        fileName,
        file.getName(),
        String.valueOf(MediaType.APPLICATION_PDF),
        IOUtils.toByteArray(input));
}

This seems to generate the MultiPartFile fine, but then it uploads to a bucket in s3, and when I try to open it I can't, it just says it can't be opened. But idk if this is a problem when generating the MultiPartFile or uploading it to s3. It doesn't break when generating it or uploading it, only when I try to open it from aws, it tries to load but it says "We cant open this file".

Does anyone know what I could be doing wrong, or what I could try? Thank you very much!

Top answer
1 of 3
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 3
1
What do you mean by a String that is a URL from a pdf? Very confusing, can you explain
🌐
Spring
docs.spring.io › spring-framework › docs › 3.2.10.RELEASE_to_3.2.11.RELEASE › Spring Framework 3.2.11.RELEASE › index.html
MultipartFile
JavaScript is disabled on your browser · Frame Alert · This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client. Link to Non-frame version
🌐
Spring
docs.spring.io › spring-framework › docs › current › javadoc-api › org › springframework › web › multipart › MultipartFile.html
MultipartFile (Spring Framework 7.0.8 API)
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.
🌐
Medium
erkanyasun.medium.com › simplifying-file-uploads-in-spring-boot-with-multipartfile-eb8bbef68dfe
Simplifying File Uploads in Spring Boot with MultipartFile | by Master Spring Ter | Medium
December 25, 2024 - File uploads are a common requirement in web applications, and Spring Boot makes it easy to handle file uploads with its built-in support for multipart file upload. In this article, we will explore how to implement file uploads in a Spring Boot application using MultipartFile.
🌐
Medium
medium.com › @AlexanderObregon › how-spring-boot-maps-file-uploads-to-multipartfile-without-manual-parsing-bdddf5e99f72
How Spring Boot Maps File Uploads to MultipartFile Without Manual Parsing
April 5, 2025 - When a form is submitted using multipart/form-data, the file input fields are passed straight into your controller method as MultipartFile parameters. It might seem like this just works on its own, but there’s a lot going on in the background to make that happen. This article will go over how that process works behind the scenes, why you don’t have to handle parsing manually, and what Spring Boot is doing behind the scenes when a file lands in your controller.
🌐
BezKoder
bezkoder.com › home › spring boot file upload example with multipart file
Spring Boot File upload example with Multipart File - BezKoder
February 4, 2024 - In this tutorial, I will show you how to upload and download files with a Spring Boot Rest APIs to/from a static folder. We also use Spring Web MultipartFile interface to handle HTTP multi-part requests. This Spring Boot App works with: – Angular 8 / Angular 10 / Angular 11 / Angular 12 / Angular […]
🌐
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.
🌐
DEV Community
dev.to › munaf_badarpura_3811f0ab1 › spring-boot-file-upload-with-multipart-support-complete-guide-o68
Spring Boot File Upload with Multipart Support: Complete Guide - DEV Community
October 17, 2025 - There are several approaches to handle file uploads in Spring Boot, each suited for specific use cases: ... Uses the MultipartFile interface to handle files sent via HTTP POST requests.