Convert file to MultiPartFile using spring

I want to convert a file to multipartfile using spring. I have done 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 get 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 fileItem is null, but is there another solution in debug mode? I have this post Convert File to MultiPartFile , but it does not work and has no solution.

+4
source share
2 answers
  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 to get a multi-page file from a File object.

+11
source
  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

  fileItem.getOutputStream(); 

because he will throw NPE otherwise.

+2
source

Source: https://habr.com/ru/post/1484599/


All Articles