Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting File to MultiPartFile with spring

Tags:

java

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.

like image 569
Doom Avatar asked Jun 05 '13 09:06

Doom


People also ask

How do I change a file to MultipartFile?

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.

What is MultipartFile?

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 ...

How do I create a multipart file in Junit?

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.


2 Answers

    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.

like image 148
despot Avatar answered Oct 23 '22 10:10

despot


    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

like image 21
Anoop George Avatar answered Oct 23 '22 11:10

Anoop George