logo image

Single and Multiple Files Upload Example in Spring MVC



Description

Spring has built in multipart support to handle file uploads in web applications with the help of MultipartResolver objects, Spring provides a MultipartResolver for use with Commons FileUpload . By default, no multipart handling will be done by Spring, so developers should implement the logic by themselves.

1) pom.xml

Add below dependency in pom.xml

	<dependency>
		<groupId>commons-fileupload</groupId>
		<artifactId>commons-fileupload</artifactId>
		<version>1.3.1</version>
	</dependency>

2) Add below code in spring configuration xml file

<beans:bean id="commonsMultipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

		 <!--  upload size -->
		<beans:property name="maxUploadSize" value="1000000" />

	</beans:bean>

3) 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>

4)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>

5) 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;
	}
}