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.

#Spring #Spring Web #MultipartFile

How to Convert a Spring MultipartFile to a File
31.70 GEEK