Last Updated on 20 September 2020   |   Print Email
In this post, I will share some code examples demonstrating uploading multiple files in a Java web application based on Spring Boot. For getting-started tutorial, you may need to check this Spring Boot File Upload Tutorial first. Note that the uploaded files will be stored in the file system on the server side.Suppose that we want to show a form in which the user is required to pick 3 files to be uploaded. So we add 3 file input to the form like this:
Here we have 3 file input fields with different names: profilePictureFile, photoIDFile and documentFile. The profilePictureFile and photoIDFile can be only images, whereas the documentFile can be of any type. And all these 3 file inputs are required.The form would look something like below in a web browser:And in the data access layer, we have an entity class that looks like follows:
As you can see, this entity class has 3 fields to store names of the uploaded files: profilePicture, photoId and document. The actual files will be stored in the file system.And below is code for the handler method in Spring MVC controller class:
As you can see, we read names of the uploaded files first – and store names in the corresponding fields of the entity class that maps to the file upload form. Then we persist the entity object to the database. And then we store the uploaded files in the file system.
Below is code of the FileUploadUtilclass:
package net.codejava;
import java.io.*;
import java.nio.file.*;
import org.springframework.web.multipart.MultipartFile;
public class FileUploadUtil {
public static void saveFile(String uploadDir, String fileName,
MultipartFile multipartFile) throws IOException {
Path uploadPath = Paths.get(uploadDir);
if (!Files.exists(uploadPath)) {
Files.createDirectories(uploadPath);
}
try (InputStream inputStream = multipartFile.getInputStream()) {
Path filePath = uploadPath.resolve(fileName);
Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ioe) {
throw new IOException("Could not save image file: " + fileName, ioe);
}
}
}
You can use the same name for all file input elements like this:
Of course then you need to access the upload file in terms of array elements.That’s some code examples showing you how to implement multiple files upload functionality in a Spring Boot application.
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Comments
Yes, it can be used to upload any kind of files, including .docs, .pdf etc.
Follow section 4. Display uploaded images in browser in this tutorial: codejava.net/.../spring-boot-file-upload-tutorial