File upload Spring MVC cross server

  • prerequisite

    • The value of enctype of form must be multipart / form data. The function of enctype is the type of request body

    • method must be post

    • Need to have < input type = "file" / > tag

    • To implement a file using the Commons file upload component, you need to import the corresponding supporting jar package of the component

      • commons-fileupload-1.3.1.jar

      • commons-io-2.4.jar

    <!-- File upload component -->
    <form action="user/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="avatar" />
        <input type="submit" value="upload" />

    Spring MVC uploading files across servers

    • Import the jar package provided by sun company

      <!-- Upload files across servers jar package -->


    • To build a picture server, simply speaking, is to create another project. Just change the HTTP port and JMX port of this project

    • If such an error occurs: PUT ****************** returned a response status of 404 Not Found, it means that the web.xml main configuration file of tomcat server needs to be modified (not the web.xml under the project directory). Just add code to the configuration file

    • If there is such an error: PUT ************* returned a response status of 409 Conflict, it means that the image server is missing the file directory. At this time, it is necessary to manually create the file saving directory under the project directory under the target of the project directory.

    • The parameter name of the controller method must be the same as the name value of the input tag of the file on the form

      import com.sun.jersey.api.client.Client;
      import com.sun.jersey.api.client.WebResource;
      import org.springframework.web.multipart.MultipartFile;
      import java.util.UUID
      public class UserController{
          public String upload(MultipartFile avatar) throws Exception{
              //Specify the server address for picture saving
              String path = "";
              String filename = avatar.getOriginalFilename();
              String uuid = UUID.randomUUID().toString().replace("-", "");
              filename = uuid+"_"+filename;
              //Create client object
              Client client = Client.create();
              //Connect to picture server
              WenResource webResource = client.resource(path+filename);
              //Upload file
              return "user";



Keywords: Java xml Spring Tomcat

Added by elle_girl on Tue, 28 Apr 2020 19:17:11 +0300