Monday, August 28, 2023

How to upload/download files in Spring MVC Java web applications? Example Tutorial

Hello guys, if you are wondering how to upload file and download files from a Spring MVC application then you have come to the right place. This is an important functionality for any real-world application and knowing how to upload a file in a Spring application is important for professional Java developers and that's what you will learn in this Spring MVC tutorial. Earlier, I have shared several Spring Boot tutorial like Spring Boot + Microservices, and Spring Boot + REST and even  how to upload files using Servlet and JSP using Apache Commons FileUpload library and In this tutorial, we are going to discuss how to upload and download files using Spring MVC. 

In general, spring makes common development tasks easier by providing out-of-box implementation so I expect this would be easier than before, so let's find out and that's why every Java developer should learn Spring Framework.

It's not only required for more of Java development but also its one of the essential skill for many Java development roles. In the past, I have also shared the best Spring courses and books for Java developers. If you have just started learning the Spring framework or want to learn Spring in-depth, you can also take a look at those resources.



How to upload/download Files on Spring Web Applications? 

This file upload is a very common task in any web application and this allows to have a good interaction with users with giving an opportunity to upload/download photos, files, and other materials through the web.

So in this article, we are focusing on what Spring offers for multipart support in web applications. So will discuss the MultipartResolver implementation for use with Apache Commons Fileupload.


1. Add CommonsMultipartResolver Dependency to your spring project

This MultipartResolver resolver variation delegated to the application's local FileUpload library, allowing for optimal portability between Servlet containers. Will see how to add the dependency to our spring application

We will use the FileNameUtils class in commons-io to normalize the file name of the uploaded file.

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>




2. Build the frontend of the system using HTML/JavaScript

Then we will focus on the file upload frontend of the application, which is used to upload
files to the backend of the system. The below code snippet shows the HTML and JavaScript which are used to upload the data to the spring backend.

<form class="form" id="file-form"
enctype="multipart/form-data">
<div class="form-group">
<label class="form-label required">
Select File (multiple supported)
</label>
<input type="file" multiple class="form-control required"
id="uploaded-file" name="uploaded-file" />
</div>
<div>&nbsp;</div>
<button class="btn btn-primary" type="submit">Upload</button>
</form>

<script>
$(function (){
$("#file-form").submit(function (){
$(this).ajaxSubmit({
beforeSubmit: function (){
return $('#file-form').valid();
},
success: function(response){
alert("Successfully uploaded the files");
},
error: function(){
alert("Error occurred while uploading the files");
},
url: '/api/upload',
type: 'POST'
});
return false;
});
});
</script>







3.Add the CommonsMultipartResolver bean into our Spring configuration 

Then we have to make use of the Spring boot's max file size
and max request size attributes to configure
he CommonsMultipartResolver.

@Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(100000);
return multipartResolver;
}

Then we have to create the API's to accept the files which is sent from 
the frontend of the application.
    
    
In there, we can use the new method copyFileUsingCommons.

<form:form method="POST" action="/students/uploadStudentFile" 
enctype="multipart/form-data">
    <table>
        <tr>
            <td>Select a file to upload</td>
            <td><input type="file" name="files" /></td>
        </tr>
        <tr>
            <td>Select a file to upload</td>
            <td><input type="file" name="files" /></td>
        </tr>
        <tr>
            <td>Select a file to upload</td>
            <td><input type="file" name="files" /></td>
        </tr>
        <tr>
            <td><input type="submit" value="Submit" /></td>
        </tr>
    </table>
</form:form>

So we can add multiple files using the above method. 
Let's discuss about the spring boot file upload.




4. Spring Boot File Upload

This is same as the normal file upload. but the spring framework makes it easier for developers to start the process of file uploading with minimum number of code lines. No servlet configuration is required because Boot will register and setup it for us if we include the web module in our dependencies.


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.5.4.RELEASE</version>
</dependency>

So from the application.properties file, we can allow maximum file upload size

to files which is uploading.


spring.servlet.multipart.max-file-size=256KB
spring.servlet.multipart.max-request-size=256KB

Other than that, we can control the location of file upload using the following code segments which is also in the application.properties file.


spring.servlet.multipart.enabled=true
spring.servlet.multipart.location=${java.io.tempDirectory}

Here the tempDirectory means the temporary location which is file is added 
to the operating system.

How to upload/download file using Spring MVC and Spring Boot ?  Example Tutorial


That's all about how to upload or download files from a Spring-based Java application. We have seen how we can use the MultipartResolver to upload files in the Java web application. Spring Boot makes this task easier and you can enable this functionality by just setting spring.servlet.multipart.enabled configuration on Spring application.properties file. 

So in this tutorial, we discussed the different file upload/download methods using Spring MVC.  see you in the next tutorial.


Other Java and Spring Tutorial you may like
  • How Spring MVC works internally? (answer)
  • Spring Boot + ThyMyleaf project example (example)
  • Difference between @Autowired and @Inject in Spring? (answer)
  • Spring Data JPA Repository (JpaReposistory example)
  • 5 Courses to learn Spring Cloud for Microservices (courses)
  • 10 Spring MVC annotations Java developer should learn (annotations)
  • Spring Data JPA @Query Example (query example)
  • 5 Courses to Learn Spring Security for Java programmers (courses)
  • Top 5 Spring Boot Annotations Java Developers should know (read)
  • 20+ Spring MVC Interview Questions for Programmers (answer)
  • Top 5 Frameworks Java Developer Should Know (frameworks)
  • 10 Advanced Spring Boot Courses for Java developers (courses)
  • Difference between @RequestParam and @PathVariable in Spring (answer)
  • Top 7  Courses to learn Microservices in Java (courses)
  • @SpringBootApplication vs @EnableAutoConfiguration? (answer)
  • 15 Spring Boot Interview Questions for Java Developers (questions)
  • Top 5 Courses to Learn and Master Spring Cloud (courses)
  • Top 5 Spring Cloud annotations Java programmer should learn (cloud)
  • Difference between @Component, @Service, and @Controller in Spring (answer)

Thanks for reading this article so far. If you find this Spring File upload and download  Example then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are a Java beginner and want to learn the Spring MVC from scratch, and looking for some best online resources then you can also check out these best Spring MVC courses for beginners. This list contains free Udemy and Pluralsight courses to learn Spring MVC from scratch.     

No comments:

Post a Comment