Upload a File using MultipartFile in Spring MVC

Posted By : Dilshad Ahmad | 31-Jul-2018

1. Use the form tag with enctype=" " in HTML/JSP.
     <form method="POST" action="uploadFile.oodles" enctype="multipart/form-data">

2. Use the <input type='file'.../> for file selection.
     <input type="file" name="file"/>

3. Copy the following jars to WEB-INF/lib directory.
      a. commons-
fileupload-1.3.1.jar
      b.
commons-io-2.4.jar

4. Copy all the spring related jars into the WEB-INF/lib directory.

5. Configure the bean with the class CommonsMultipartResolver by specifying the information about the file that will be uploaded.

     @Bean
     public CommonsMultipartResolver commonsMultipartResolver(){
     CommonsMultipartResolver viewResolver = new CommonsMultipartResolver();
     viewResolver.setMaxUploadSize(500000);
     return viewResolver;
     }

6. Implement the required method in the controller class.

7. Use the following annotation with the implemented method.

     @RequestMapping(value = "/uploadFile.oodles", method=RequestMethod.POST)

8. Define the MultipartFile as parameter for the method to collect the upload file data.

     a. For Single File

              MultipartFile file
 
     b. For Multiple File
              MultipartFile[] files
 
9. Define the RequestParam annotation with MultipartFile.
     a. For Single File
              @RequestParam("file") MultipartFile file
 
     b. For Multiple File
              @RequestParam("file") MultipartFile[] files
 
10. Controller class will looks like -
    @Controller
	public class FileUploadController{
	@RequestMapping(value="/uploadFile.oodles", method=RequestMethod.POST)
	public String uploadFile(@RequestParam("name") String name, @RequestParam("file") MultipartFile file, HttpServletRequest 
    req){
          .....
          .....
          .....
          return "success";
    }
}

11. Perform the follwing in the implemented method.
      a. Check whether the file is empty or not.

     if(file.isEmpty()){
     req.setAttribute("MSG", file.getOriginalFileName()+" is empty.");
     return "error";

     b. We can use the following method with MultipartFile to get the original file name.
                  String fileName = file.getOriginalFileName();

     c. Read the data from the MultipartFile and write to destination file.

     File file=new File(directory, fileName);
     BufferedOutputStream bufferedOutputStream =new BufferedOutputStream(new FileOutputStram(file));
     byte data[] = file.getBytes();
     bufferedOutputStream.write(data);
     bufferedOutputStream.close();

 

Controller Class:


package com.java;

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

@Controller
public class UploadController {
	@RequestMapping(value = { "/uploadFile.oodles" }, method = RequestMethod.POST)
	public String uploadFile(@RequestParam("name") String name, @RequestParam("file") MultipartFile file,
			HttpServletRequest request) {
		if (file.isEmpty()) {
			request.setAttribute("MSG", file.getOriginalFilename() + " is Empty.");
			return "error";
		} else {
			try {
				String path = "D://FileUpload";
				File directory = new File(path);
				if (!directory.exists()) {
					directory.mkdirs();
				}
				String fileName = file.getOriginalFilename();
				File f = new File(directory, fileName);
				BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(f));
				byte[] data = file.getBytes();
				bufferedOutputStream.write(data);
				bufferedOutputStream.close();
				request.setAttribute("MSG", f.getAbsolutePath());
				return "success";

			} catch (Exception e) {
				e.printStackTrace();
				req.setAttribute("MSG", file.getOriginalFilename() + ". " + e.getMessage());
				return "error";
			}
		}
	}
}

Thanks

About Author

Author Image
Dilshad Ahmad

Dilshad Ahmad working as a Developer is always ready to face challenges and likes to work with full dedication and coordination.

Request for Proposal

Name is required

Comment is required

Sending message..