File upload and Tomcat mapping path setting of Spring MVC

File upload and Tomcat mapping path setting of Spring MVC

catalog

summary:

  • Spring MVC provides direct support for file upload, which is implemented through plug and play MultipartResolver. Spring uses Jakarta Commons FileUpload to implement a MultipartResolver class CommonsMultipartResolver

  • Spring MVC is not equipped with MultipartResolver by default, so file upload cannot be processed by default. If you want to use spring's file upload function, you need to configure it as follows.

  • The mapping path setting of Tomcat is also involved here.

To configure MultipartResolver:

  • Import the dependent packages needed for file upload
  <!-- File upload dependency -->
      <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.4</version>
      </dependency>
  • First, you need to configure a MultipartResolver parser to add configuration information to your springxml file:
   	<bean id="multipartResolver"
	    class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
	    p:defaultEncoding="UTF-8" 
	    p:maxUploadSize="5242880"
	    p:uploadTempDir="file:/d:/temp"/>

  • defaultEncoding: (optional) the encoding format of the request, which is ISO-8859-1 by default, must be consistent with the pageEncoding attribute of the user JSP, so as to correctly read the content of the form.

  • uploadTempDir: (optional) the upper limit of the upload file size, in bytes (5MB), is the temporary directory used in the process of file upload. After the file is uploaded, the temporary files in the temporary directory will be automatically cleared.

  • uploadTempDir: (optional) temporary file path

  • It should also be noted that the class packages of Jakarta Commons FileUpload and Jakarta Commons io need to be added to the class path.

Tomcat configuration

  • Open conf under Tomcat installation directory ----- > server.xml , add the following information under the text label:
  <Context path="/images" docBase="F:\\Goktech-Web frame\\Work items\\images"/>
  • Path is the mapping path; docBase is the local path.

Configuration of tomcat deployment in IDEA

  • To be able to use the mapping path, you need to configure it in tomcat in idea
    • Select the local path you need to map, click OK to complete the setup
    • After setting, the following results will appear

Controllers and pages:

  • I will take the picture upload as an example, and finally display it on the page:
  • PhotoController.java
@RequestMapping("/upload")
    public ModelAndView upload(MultipartFile photo, HttpServletRequest req){
        ModelAndView modelAndView = new ModelAndView();
        String photo_name = "";
        try {
            // Picture upload
            String pathRoot = req.getServletContext().getRealPath("");
            System.out.println("Root path:" + pathRoot);
            // UUID resets the picture name, and no picture overwrite occurs during storage
            String fileName = UUID.randomUUID().toString().replace("-","");
            photo_name = fileName + ".jpg";
            // Local file storage path, where the path needs to be consistent with Tomcat's server.xml  Path always
            photo.transferTo(new File("F:\\Goktech-Web frame\\Work items\\images\\" + photo_name));
            System.out.println("==========Picture uploaded successfully==========");
            modelAndView.addObject("photo_name", photo_name);
            modelAndView.setViewName("success");
        } catch (IOException e) {
            System.out.println("==========Image upload failed==========");
            e.printStackTrace();
        }
        return modelAndView;
    }
  • upload.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %> <!-- set up false have access to el expression -->
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
    <title>Upload picture</title>
</head>
<body>
    <h2>Upload picture</h2>
    <!--We need to add enctype Property to specify the form content type to support file upload-->
    <form action="${path}/upload" method="post" enctype="multipart/form-data"> 
        Picture:<input name="photo" type="file"/>
        <input type="submit" value="Submit"/>
    </form>
</body>
</html>
  • success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
    <title>display picture</title>
</head>
<body>
    <h2>display picture</h2>
    <div>
        <!--here /images/ Use you directly server.xml The mapping path configured in-->
        Picture:<img src="/images/${photo_name}"/>
    </div>
</body>
</html>

Results:

Tags: Tomcat Spring JSP xml

Posted on Fri, 19 Jun 2020 01:07:28 -0400 by w4designs