spring mvc: file upload

Before talking about file upload, let's talk about the classes that will be used.

MultipartFile (file upload)--CommonsMultipartResolver 

In SpringMVC, file upload is achieved through MultipartResolver. Therefore, if you want to upload files, you only need to register the corresponding MultipartResolver in spring-mvc.xml.

There are two implementation classes of MultipartResolver:

  1. CommonsMultipartResolver
  2. StandardServletMultipartResolver

The difference between the two:

  1. The first requires the use of jar packages such as Apache's commons-fileupload support, but it can be used in older servlet versions.
  2. The second one does not require third-party jar package support, it uses the built-in upload function of the servlet, but can only be used in Servlet 3 and above.

The first use step:

/*CommonsMultipartResolver uploads two packages*/ 

"commons-fileupload:commons-fileupload:1.3.1",

"commons-io:commons-io:2.4"
<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver">



the second:
<!--2 Register and upload StandardServletMultipartResolver
        The second one does not require third-party jar package support, it uses the built-in upload function of the servlet,
        But it can only be used in versions above Servlet 3.
        -->

 

Springmvc's @Validated annotation uses

3. Add @Validated before the pojo that needs to be verified, and add BindingResult bindingResult after the pojo that needs to be verified to receive the verification error information

Note: @Validated and BindingResult bindingResult are paired, and the order of parameters is fixed (one before the other).

 

 

 

 

File Upload:

1. Configure in xxx-servlet.xml file, spring mvc file upload class bean configuration

<bean id="multipartResolver"   
 class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

2. Create a new FileModel class, inherit org.springframework.web.multipart.MultipartFile file upload

import org.springframework.web.multipart.MultipartFile;

public class FileModel {
   private MultipartFile file;

   public MultipartFile getFile() {
      return file;
   }

   public void setFile(MultipartFile file) {
      this.file = file;
   }
}

3. Create a new template file

file.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title>Spring MVC upload file example</title>
</head>
<body>
    <form:form method="POST" modelAttribute="fileUpload"
        enctype="multipart/form-data">
      Please select a file to upload:
      <input type="file" name="file" />
        <input type="submit" value="Submit upload" />
    </form:form>
</body>
</html>

  

Upload results page

file_result.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<html>
<head>
<title>Spring MVC upload file example</title>
</head>
<body>
    file name :
    <b> ${fileName} </b> - Upload successful!
</body>
</html>

  

4. Upload the program

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class FileUploadController {

   @Autowired
   ServletContext context;

   @RequestMapping(value = "/fileUploadPage", method = RequestMethod.GET)
   public ModelAndView fileUploadPage() {
      FileModel file = new FileModel();
      ModelAndView modelAndView = new ModelAndView("fileUpload", "command", file);
      return modelAndView;
   }

   @RequestMapping(value="/fileUploadPage", method = RequestMethod.POST)
   public String fileUpload(@Validated FileModel file, BindingResult result, ModelMap model) throws IOException {
      if (result.hasErrors()) {
         System.out.println("validation errors");
         return "fileUploadPage";
      } else {            
         System.out.println("Fetching file");
         MultipartFile multipartFile = file.getFile();
         String uploadPath = context.getRealPath("") + File.separator + "temp" + File.separator;
         //Now do something with file...
         FileCopyUtils.copy(file.getFile().getBytes(), new File(uploadPath+file.getFile().getOriginalFilename()));
         String fileName = multipartFile.getOriginalFilename();
         model.addAttribute("fileName", fileName);
         return "success";
      }
   }
}

  

The fileUpload in the public ModelAndView fileUploadPage() code block is matched with the fileUpload in file.jsp: modelAttribute="fileUpload"

Among them, @Validated in the code block of public String fileUpload(@Validated FileModel file, BindingResult result, ModelMap model) is used to validate the data, and the validation data is used together with BindingResult. FileModel file is the file(fileUpload) submitted in file.jsp

 

  

  

 

 

 

In SpringMVC, file upload is achieved through MultipartResolver. Therefore, if you want to upload files, you only need to register the corresponding MultipartResolver in spring-mvc.xml.

There are two implementation classes of MultipartResolver:

  1. CommonsMultipartResolver
  2. StandardServletMultipartResolver

The difference between the two:

  1. The first requires the use of jar packages such as Apache's commons-fileupload support, but it can be used in older servlet versions.
  2. The second one does not require third-party jar package support, it uses the built-in upload function of the servlet, but can only be used in Servlet 3 and above.

The first use step:

/*CommonsMultipartResolver uploads two packages*/ 

"commons-fileupload:commons-fileupload:1.3.1",

"commons-io:commons-io:2.4"
<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver">



the second:
<!--2 Register and upload StandardServletMultipartResolver
        The second one does not require third-party jar package support, it uses the built-in upload function of the servlet,
        But it can only be used in versions above Servlet 3.
        -->

 

Springmvc's @Validated annotation uses

3. Add @Validated before the pojo that needs to be verified, and add BindingResult bindingResult after the pojo that needs to be verified to receive the verification error information

Note: @Validated and BindingResult bindingResult are paired, and the order of parameters is fixed (one before the other).

 

 

 

 

File Upload:

1. Configure in xxx-servlet.xml file, spring mvc file upload class bean configuration

<bean id="multipartResolver"   
 class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

2. Create a new FileModel class, inherit org.springframework.web.multipart.MultipartFile file upload

import org.springframework.web.multipart.MultipartFile;

public class FileModel {
   private MultipartFile file;

   public MultipartFile getFile() {
      return file;
   }

   public void setFile(MultipartFile file) {
      this.file = file;
   }
}

3. Create a new template file

file.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title>Spring MVC upload file example</title>
</head>
<body>
    <form:form method="POST" modelAttribute="fileUpload"
        enctype="multipart/form-data">
      Please select a file to upload:
      <input type="file" name="file" />
        <input type="submit" value="Submit upload" />
    </form:form>
</body>
</html>

  

Upload results page

file_result.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<html>
<head>
<title>Spring MVC upload file example</title>
</head>
<body>
    file name :
    <b> ${fileName} </b> - Upload successful!
</body>
</html>

  

4. Upload the program

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class FileUploadController {

   @Autowired
   ServletContext context;

   @RequestMapping(value = "/fileUploadPage", method = RequestMethod.GET)
   public ModelAndView fileUploadPage() {
      FileModel file = new FileModel();
      ModelAndView modelAndView = new ModelAndView("fileUpload", "command", file);
      return modelAndView;
   }

   @RequestMapping(value="/fileUploadPage", method = RequestMethod.POST)
   public String fileUpload(@Validated FileModel file, BindingResult result, ModelMap model) throws IOException {
      if (result.hasErrors()) {
         System.out.println("validation errors");
         return "fileUploadPage";
      } else {            
         System.out.println("Fetching file");
         MultipartFile multipartFile = file.getFile();
         String uploadPath = context.getRealPath("") + File.separator + "temp" + File.separator;
         //Now do something with file...
         FileCopyUtils.copy(file.getFile().getBytes(), new File(uploadPath+file.getFile().getOriginalFilename()));
         String fileName = multipartFile.getOriginalFilename();
         model.addAttribute("fileName", fileName);
         return "success";
      }
   }
}

  

The fileUpload in the public ModelAndView fileUploadPage() code block is matched with the fileUpload in file.jsp: modelAttribute="fileUpload"

Among them, @Validated in the code block of public String fileUpload(@Validated FileModel file, BindingResult result, ModelMap model) is used to validate the data, and the validation data is used together with BindingResult. FileModel file is the file(fileUpload) submitted in file.jsp

 

  

  

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324773283&siteId=291194637