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.

Gueorgui Obregon
  • 5,077
  • 3
  • 33
  • 57
Doom
  • 1,258
  • 3
  • 15
  • 24

2 Answers2

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

Anoop George
  • 742
  • 6
  • 6
6
    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.

despot
  • 7,167
  • 9
  • 44
  • 63