Converting File to MultiPartFile Converting File to MultiPartFile spring spring

Converting File to MultiPartFile


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


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


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.