简体   繁体   中英

Converting File to MultiPartFile with spring

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.

    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

    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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM