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
๐ŸŒ
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
Discussions

java - How to convert a multipart file to File? - Stack Overflow
I had used your code for converting the file. So I changed the properties in the applicationcontext.xml to get rid of the memory limitations. And it works !!! 2017-04-09T17:41:54.61Z+00:00 ... While creating a file from multipart file, it should be kept in memory. More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - Converting File to MultiPartFile with spring - Stack Overflow
This is another way of getting multipart file from File object ... I'd like to point out that MockMultipartFile is in org.springframework.mock.web. And, this works nicely. ... I saw the same issue Vipul did. Errors when trying to use in real business logic. More on stackoverflow.com
๐ŸŒ stackoverflow.com
April 20, 2017
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
How to create a Multipart file using java - Stack Overflow
Explore Stack Internal ... Save this question. Show activity on this post. I am trying to use create Multipart files and upload these files using my Java Spring MVC web application. I could not find any documentation to create a multipart file using Java, so I tried to create a file and then convert ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ spring โ€บ spring web โ€บ convert byte[] to multipartfile in java
Convert byte[] to MultipartFile in Java | Baeldung
August 15, 2024 - Therefore the details about the file name or content type can be provided as custom logic. As a result, weโ€™ve returned null here. Weโ€™ve also provided our own implementation for the other required methods from the interface: public class CustomMultipartFile implements MultipartFile { //previous methods @Override public boolean isEmpty() { return input == null || input.length == 0; } @Override public long getSize() { return input.length; } @Override public byte[] getBytes() throws IOException { return input; } @Override public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(input); } @Override public void transferTo(File destination) throws IOException, IllegalStateException { try(FileOutputStream fos = new FileOutputStream(destination)) { fos.write(input); } } }
๐ŸŒ
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 - There are many use cases when we need to convert input stream to MultipartFile i am sharing you the method by which you can easily convert Input stream to MultipartFile using java. Please have a look on below method. 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
๐ŸŒ
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.
Find elsewhere
๐ŸŒ
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 - Furthermore, we invoke the getOutputStream() method on the DiskFileItem object and use the copy() from the Apache Commons IO library to copy from InputStream to OutputStream. The copy() method saves the file content to the DiskFileItem object. Finally, we create the CommonsMultipartFile object which accepts the DiskFileItem and completes the File to MultipartFile conversion. Notably, this is the best approach for converting File to MultipartFile in production applications.
๐ŸŒ
javathinking
javathinking.com โ€บ blog โ€บ convert-file-to-multipartfile-java-spring-boot
Convert File to MultipartFile in Java Spring Boot โ€” javathinking.com
Use different types of files and file sizes in your tests. Converting a File to a MultipartFile in a Java Spring Boot application can be easily achieved using the MockMultipartFile class.
๐ŸŒ
Javathinking
javathinking.com โ€บ blog โ€บ how-to-convert-string-to-multipart-file-in-java
How to Convert String to Multipart File in Java | JavaThinking.com
July 20, 2025 - In Java development, there are often scenarios where you need to convert a string into a MultipartFile object. The MultipartFile interface in Spring Framework is used to handle file uploads.
๐ŸŒ
Electro4u
electro4u.net โ€บ blog โ€บ convert-byte-to-multipartfile-in-java-1319
Convert Byte[] to MultipartFile in Java with electro4u.net
Now, you can use the multipartFile object in your file handling logic. ... 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); ...
๐ŸŒ
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?
๐ŸŒ
Google Groups
groups.google.com โ€บ g โ€บ rest-assured โ€บ c โ€บ RS8dWs0G7XQ
Java Object to Multipart
given().multiPart("controlName", object, "application/json"). .. See documentation. ... Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message ... When i do that i get: com.fasterxml.jackson.databind.JsonMappi...
๐ŸŒ
CodingNomads
codingnomads.com โ€บ spring-web-multipart-data
Multipart Form Data Handling
Enable the servlet to accept multipart requests. Set the maximum size of requests and files.
๐ŸŒ
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
๐ŸŒ
Medium
raynermdz.medium.com โ€บ handy-java-multipart-file-uploader-3ab065aee43a
Handy Java Multipart File Uploader | by Rayner Mendez | Medium
October 1, 2021 - With this class, you can upload, change the name of the file, and as a bonus you can generate a random name for the file in your Java application. ... This is where the magic happens. This method takes care of calling the other methods in the class to upload the file. It takes a directory as a string, a MultipartFile, and a name as a string.