spring mvc file upload (on)

SpringMVC upload files are processed through MultipartResolver (Multipart parser), which is an interface for MultipartResolver, which has two implementation classes

CommonsMultipartResolver Relying on the Jakarta Common FileUplode project under Apache to parse Multipart requests, it can be used in various versions of spring, but it can only be achieved by relying on third-party implementation packages
StandardServletMultipartResolver It is the product after spring 3.1, it depends on the implementation of Servlet 3.0 or higher, it does not need to depend on third-party packages

You can use CommonsMultipartResolver to upload files, or you can use StandardServletMultipartResolver to upload files. Let's take CommonsMultipartResolver as an example to upload files to see how to write them.

Using CommonsMultipartResolver
1. When using CommonsMultipartResolver, you need to depend on two packages, you can add the dependencies of these two packages in pom.xml Apache's commons-io and commons-fileupload
2. Configure the CommonsMultipartResolver bean in the applicationContext.xml file

<!-- To use CommonsMultipartResolver it needs to import two dependencies-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <!-- Maximum uploads-->  

  <property name="maxUploadSize">
    <value>104857600</value>
  </property>

   <!-- The maximum number of bytes to read a file into memory, usually 1024 -->
  <property name="maxInMemorySize">
    <value>4096</value>
  </property>
</bean>

Now we can write the controller to receive the file submission request from the foreground

front desk:

Front page

<form method="post" action="./uploadPart" enctype="multipart/form-data"><!-- The submission encoding type of the uploaded file should be multipart/form-data-->
  <input type="file " name="file" value="Please select the uploaded file">
  <input type="submit" value="Submit">
</form>

Background (there are two ways to handle file upload requests):

The first: HttpServletRequest

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public ModelAndView uploadFile(HttpServletRequest request) {
  //Convert
  MultipartHttpServletRequest msq = (MultipartHttpServletRequest) request;
  //Get the uploaded file
  MultipartFile file = msq.getFile( "file");

  ModelAndView mv = new ModelAndView();
  mv.setView(new MappingJackson2JsonView());// Make the return result in json format
  // Create file save path
  String filename = request.getSession().getServletContext(). getRealPath("/") + "upload/";

  // 判断保存路径是否存在,不存在则创建 mkdirs表示创建多层目录 mkdir只能创建一层
  File dest = new File(filename);
  if (!dest.exists()) {
    dest.mkdirs();
  }
  try {
    //获取原始文件名
    filename += file.getOriginalFilename();
    File actdest = new File(filename);//目标文件
    //保存文件
    file.transferTo(actdest);
    mv.addObject("success", true);
    mv.addObject("msg", "上传文件成功");
  } catch (IllegalStateException | IOException e) {
    mv.addObject("success", false);
    mv.addObject("msg", "上传文件失败");
    e.printStackTrace();
  }
  return mv;
}

 

第二种:MultipartFile

@RequestMapping(value = "/uplodeFileMultipartFile", method = RequestMethod.POST)
public ModelAndView uplodeFileMultipartFile(MultipartFile file, HttpServletRequest request) {
  ModelAndView mv = new ModelAndView();
  mv.setView(new MappingJackson2JsonView());
  // 获取原始路径名
  String fileName = file.getOriginalFilename();
  file.getContentType();
  // 配置存储文件路径
  String path = request.getSession().getServletContext().getRealPath("/") + "upload/";
  try {
      File filemkdirs = new File(path);
      if (!filemkdirs.exists()) {
        filemkdirs.mkdirs();
      }
      path += fileName;
      File dest = new File(path);
      file.transferTo(dest);
      mv.addObject("success", true);
      mv.addObject("msg", "上传文件成功!");
    } catch (IllegalStateException | IOException e) {
      e.printStackTrace();
      mv.addObject("success", false);
      mv.addObject("msg", "上传文件失败!");
    }
    return mv;
}

 

Guess you like

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