Uploading Single and Multiple Files Example with Spring Boot


We can implement upload file logic in spring boot by using two components

  1. Thymeleaf
  2. FreeMarker

**Thymeleaf **

Thymeleaf is a Java XML or XHTML or HTML5 template engine that can be used both in web and non-web applications. It is better to use for serving XHTML or HTML5 at the presentation layer of MVC based web applications
In web applications Thymeleaf mainly substitutes for JSP, Thymeleaf's main goal is to bring elegant natural templates to your development, allowing for stronger collaboration in development teams.

**FreeMarker **

Apache FreeMarker is also templating engine: a Java library to generate text output like HTML web pages, e-mails, configuration files, source code, etc.

**Following is some sample code **
1) pom.xml
we need to add following dependencies in pom.xml either one of them.

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency> 

               or

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>


2) singlefileupload.jsp

<html>
<body>
	<form method="POST" action="/upload/singleFileUpload" enctype="multipart/form-data">
		Please select a File <input type="file" name="file">
 
		File Description: <input type="text" name="description">
 
 
		<input type="submit" value="Upload"> click me to upload the file.
	</form>	
</body>
</html>

3)mutliplefilesupload.jsp


<html>
<body>
	<form method="POST" action="/upload/uploadMultipleFiles" enctype="multipart/form-data">
		Please select file1 :<input type="file" name="file">
 
		File Description1: <input type="text" name="description">
 
 
		Please select file2 :<input type="file" name="file">
 
		File Description2 : <input type="text" name="description">
 

		<input type="submit" value="Upload"> click me to upload the files
	</form>
</body>
</html>

4) MultiFileUploadController .java


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@RestController 
@RequestMapping(value ="/upload”)

public class MultiFileUploadController {

private static String UPLOADED_FOLDER = "E://uploadedfiles//";

@RequestMapping(value = "/singleFileUpload ", method = RequestMethod.POST)
public String uploadSingleFile(@RequestParam("description ") String description,@RequestParam("file") MultipartFile file) {

             String status="";
		if (!file.isEmpty()) {
			try {
			byte[] bytes = file.getBytes();
			File dir = new File(UPLOADED_FOLDER)	
			if (!dir.exists())
					dir.mkdirs();
                                
					
                File uploadFile = new File(dir.getAbsolutePath()+ File.separator + 
                                         file.getOriginalFilename());
                BufferedOutputStream outputStream = new BufferedOutputStream(
                                new FileOutputStream(uploadFile));
				outputStream.write(bytes);
				outputStream.close();

				status = status +  " Successfully uploaded file=" + file.getOriginalFilename();
			} catch (Exception e) {
				status = status +  "Failed to upload " + file.getOriginalFilename()+ " " + e.getMessage();
			}
		}
return status; 
	}

	@RequestMapping(value = "/uploadMultipleFiles ", method =RequestMethod.POST)
public  String uploadMultipleFiles(@RequestParam("description") String[] descriptions,@RequestParam("file") MultipartFile[] files) {

		if (files.length != descriptions.length)
			return "Mismatching no of files are equal to description";

		String status = "";
        File dir = new File(UPLOADED_FOLDER)
		for (int i = 0; i < files.length; i++) {
			MultipartFile file = files[i];
			String description = descriptions[i];
			try {
				byte[] bytes = file.getBytes();

				if (!dir.exists())
					dir.mkdirs();

				File uploadFile = new File(dir.getAbsolutePath()
						+ File.separator + file.getOriginalFilename());
				BufferedOutputStream outputStream = new BufferedOutputStream(
						new FileOutputStream(uploadFile));
				outputStream.write(bytes);
				outputStream.close();

				status = status + "You successfully uploaded file=" + file.getOriginalFilename();
			} catch (Exception e) {
				status = status + "Failed to upload " + file.getOriginalFilename()+ " " + e.getMessage();
			}
		}
		return status;
	}
}

5)FileUploadMain.java


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.File;
import java.io.IOException;

@SpringBootApplication
public class FileUploadMain {
    public static void main(String[] args) throws IOException {
        SpringApplication.run(FileUploadMain.class, args);
    }
}