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);
but receive this exception:
threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at org.apache.commons.fileupload.disk.DiskFileItem.getSize(DiskFileItem.java:316)
i think that fileItem is null but on debug mode is populated, there is another solution? I have this post Converting File to MultiPartFile but not work and not have solution.
MultipartFile#transferTo Using the transferTo() method, we simply have to create the File that we want to write the bytes to, then pass that file to the transferTo() method. The transferTo() method is useful when the MultipartFile only needs to be written to a File.
public interface MultipartFile extends InputStreamSource. A representation of an uploaded file received in a multipart request. The file contents are either stored in memory or temporarily on disk. In either case, the user is responsible for copying file contents to a session-level or persistent store as and if desired ...
I have done the multipart file as a input for junit by using [MockMultipartFile]. FileInputStream inputFile = new FileInputStream( "path of the file"); MockMultipartFile file = new MockMultipartFile("file", "NameOfTheFile", "multipart/form-data", inputFile); now use the file input as multipart file. Save this answer.
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
fileItem.getOutputStream();
because it will throw NPE otherwise.
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));
This is another way of getting multipart file from File object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With