Spring Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

1. Overview

In this quick tutorial, we'll cover various ways of converting a Spring MultipartFile to a File.

2. MultipartFile#getBytes

MultipartFile has a getBytes() method that returns a byte array of the file's contents. We can use this method to write the bytes to a file:

MultipartFile multipartFile = new MockMultipartFile("sourceFile.tmp", "Hello World".getBytes());

File file = new File("src/main/resources/targetFile.tmp");

try (OutputStream os = new FileOutputStream(file)) {
    os.write(multipartFile.getBytes());
}

assertThat(FileUtils.readFileToString(new File("src/main/resources/targetFile.tmp"), "UTF-8"))
  .isEqualTo("Hello World");

The getBytes() method is useful for instances where we want to perform additional operations on the file before writing to disk, like computing a file hash.

3. MultipartFile#getInputStream

Next, let's look at MultipartFile‘s getInputStream() method:

MultipartFile multipartFile = new MockMultipartFile("sourceFile.tmp", "Hello World".getBytes());

InputStream initialStream = multipartFile.getInputStream();
byte[] buffer = new byte[initialStream.available()];
initialStream.read(buffer);

File targetFile = new File("src/main/resources/targetFile.tmp");

try (OutputStream outStream = new FileOutputStream(targetFile)) {
    outStream.write(buffer);
}

assertThat(FileUtils.readFileToString(new File("src/main/resources/targetFile.tmp"), "UTF-8"))
  .isEqualTo("Hello World");

Here we're using the getInputStream() method to get the InputStream, read the bytes from the InputStream, and store them in the byte[] buffer. Then we create a File and OutputStream to write the buffer contents.

The getInputStream() approach is useful in instances where we need to wrap the InputStream in another InputStream, say for example a GZipInputStream if the uploaded file was gzipped.

4. MultipartFile#transferTo

Finally, let's look at MultipartFile‘s transferTo() method:

MultipartFile multipartFile = new MockMultipartFile("sourceFile.tmp", "Hello World".getBytes());

File file = new File("src/main/resources/targetFile.tmp");

multipartFile.transferTo(file);

assertThat(FileUtils.readFileToString(new File("src/main/resources/targetFile.tmp"), "UTF-8"))
  .isEqualTo("Hello World");

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.

5. Conclusion

In this tutorial, we explored ways of converting a Spring MultipartFile to a File.

As usual, all code examples can be found over on GitHub.

Spring bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
guest
0 Comments
Inline Feedbacks
View all comments