10

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.

1

2 Answers 2

17
    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

Sign up to request clarification or add additional context in comments.

3 Comments

I'd like to point out that MockMultipartFile is in org.springframework.mock.web. And, this works nicely.
it only works in case of test environment only, otherwise it gives error
I saw the same issue Vipul did. Errors when trying to use in real business logic.
7
    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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.