Converting File to MultiPartFile

JavaSpringGroovy

Java Problem Overview


Is there any way to convert a File object to MultiPartFile? So that I can send that object to methods that accept the objects of MultiPartFile interface?

File myFile = new File("/path/to/the/file.txt")

MultiPartFile ....?

def (MultiPartFile file) {
  def is = new BufferedInputStream(file.getInputStream())
  //do something interesting with the stream
}

Java Solutions


Solution 1 - Java

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);

Solution 2 - Java

File file = new File("src/test/resources/input.txt");
FileInputStream input = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile("file",
    		file.getName(), "text/plain", IOUtils.toByteArray(input));

Solution 3 - Java

MultipartFile multipartFile = new MockMultipartFile("test.xlsx", new FileInputStream(new File("/home/admin/test.xlsx")));

This code works fine for me. May be you can have a try.

Solution 4 - Java

In my case, the

fileItem.getOutputStream();

wasn't working. Thus I made it myself using IOUtils,

File file = new File("/path/to/file");
FileItem fileItem = new DiskFileItem("mainFile", Files.probeContentType(file.toPath()), false, file.getName(), (int) file.length(), file.getParentFile());

try {
    InputStream input = new FileInputStream(file);
    OutputStream os = fileItem.getOutputStream();
    IOUtils.copy(input, os);
    // Or faster..
    // IOUtils.copy(new FileInputStream(file), fileItem.getOutputStream());
} catch (IOException ex) {
    // do something.
}

MultipartFile multipartFile = new CommonsMultipartFile(fileItem);

Solution 5 - Java

This is a solution without creating manually a file on disc :

MultipartFile fichier = new MockMultipartFile("fileThatDoesNotExists.txt",
            "fileThatDoesNotExists.txt",
            "text/plain",
            "This is a dummy file content".getBytes(StandardCharsets.UTF_8));

Solution 6 - Java

File file = new File("src/test/resources/validation.txt");
DiskFileItem fileItem = new DiskFileItem("file", "text/plain", false, file.getName(), (int) file.length() , file.getParentFile());
fileItem.getOutputStream();
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);

You need the following to prevent NPE.

fileItem.getOutputStream();

Also, you need to copy the file content to fileItem so that file won't be empty

new FileInputStream(f).transferTo(item.getOutputStream());

Solution 7 - Java

Solution without Mocking class, Java9+ and Spring only.

FileItem fileItem = new DiskFileItemFactory().createItem("file",
    Files.probeContentType(file.toPath()), false, file.getName());

try (InputStream in = new FileInputStream(file); OutputStream out = fileItem.getOutputStream()) {
    in.transferTo(out);
} catch (Exception e) {
    throw new IllegalArgumentException("Invalid file: " + e, e);
}

CommonsMultipartFile multipartFile = new CommonsMultipartFile(fileItem);

Solution 8 - Java

If you can't import MockMultipartFile using

import org.springframework.mock.web.MockMultipartFile;

you need to add the below dependency into pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

Solution 9 - Java

It's working for me:

File file = path.toFile();
String mimeType = Files.probeContentType(path);		
	
DiskFileItem fileItem = new DiskFileItem("file", mimeType, false, file.getName(), (int) file.length(),
			file.getParentFile());
fileItem.getOutputStream();
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);

Solution 10 - Java

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

public static void main(String[] args) {
		convertFiletoMultiPart();
	}

	private static void convertFiletoMultiPart() {
		try {
			File file = new File(FILE_PATH);
			if (file.exists()) {
				System.out.println("File Exist => " + file.getName() + " :: " + file.getAbsolutePath());
			}
			FileInputStream input = new FileInputStream(file);
			MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain",
					IOUtils.toByteArray(input));
			System.out.println("multipartFile => " + multipartFile.isEmpty() + " :: "
					+ multipartFile.getOriginalFilename() + " :: " + multipartFile.getName() + " :: "
					+ multipartFile.getSize() + " :: " + multipartFile.getBytes());
		} catch (IOException e) {
			System.out.println("Exception => " + e.getLocalizedMessage());
		}
	}

This worked for me.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbirdyView Question on Stackoverflow
Solution 1 - JavaArunView Answer on Stackoverflow
Solution 2 - JavaAnoop GeorgeView Answer on Stackoverflow
Solution 3 - Javauser8840900View Answer on Stackoverflow
Solution 4 - JavaGeorgios SyngouroglouView Answer on Stackoverflow
Solution 5 - JavaihebihebView Answer on Stackoverflow
Solution 6 - JavadespotView Answer on Stackoverflow
Solution 7 - JavaMariuszSView Answer on Stackoverflow
Solution 8 - JavaeRobot View Answer on Stackoverflow
Solution 9 - JavaPurushottam SadhView Answer on Stackoverflow
Solution 10 - JavaSidhajyotiView Answer on Stackoverflow