English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Example of file upload with other parameters implemented by spring mvc

This is the main jar file used: spring mvc +apache common-fileuplad

Step 1: web.xml file. [The focus is on the spring mvc interceptors and related listeners]

<?xml version="1.0" encoding="UTF-8"?> 
<web-app version="2.5"  
  xmlns="http://java.sun.com/xml/ns/javaee"  
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  
  http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 
 <display-name></display-name>  
 <!-- Spring and mybatis configuration files --> 
  <context-param> 
    <param-name>contextConfigLocation</param-name> 
    <param-value>classpath:spring-mybatis.xml</param-value> 
  </context-param> 
  <!-- Encoding Filter --> 
  <filter> 
    <filter-name>encodingFilter</filter-name> 
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>    
    <init-param> 
      <param-name>encoding</param-name> 
      <param-value>UTF-8</param-value> 
    </init-param> 
  </filter> 
  <filter-mapping> 
    <filter-name>encodingFilter</filter-name> 
    <url-pattern>/*</url-pattern> 
  </filter-mapping> 
  <!-- Spring listener --> 
  <listener> 
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
  </listener> 
  <!-- Prevent Spring memory overflow listener --> 
  <listener> 
    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> 
  </listener> 
  <!-- Spring MVC servlet --> 
  <servlet> 
    <servlet-name>SpringMVC</servlet-name> 
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
    <init-param> 
      <param-name>contextConfigLocation</param-name> 
      <param-value>classpath:spring-mvc.xml</param-value> 
    </init-param> 
    <load-on-startup>1</load-on-startup>     
  </servlet> 
  <servlet-mapping> 
    <servlet-name>SpringMVC</servlet-name> 
    <!-- Here it can be configured to*.do, corresponding to the suffix habit of struts --> 
    <url-pattern>/</url-pattern> 
  </servlet-mapping> 
  <welcome-file-list> 
    <welcome-file>/index.jsp</welcome-file> 
  </welcome-file-list> 
</web-app> 

Second step: spring-Mvc configuration file [Key: spring mvc view mode, spring mvc file upload limit parameters, spring mvc resource interception management, and others]

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" 
  xmlns:context="http://www.springframework.org/schema/context" 
  xmlns:mvc="http://www.springframework.org/schema/mvc" 
  xsi:schemaLocation="http://www.springframework.org/schema/beans  
            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
            http://www.springframework.org/schema/context  
            http://www.springframework.org/schema/context/spring-context-3.1.xsd  
            http://www.springframework.org/schema/mvc  
            http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> 
  <!-- Automatically scan the package, so that SpringMVC considers the classes annotated with @controller under the package as controllers --> 
  <mvc:annotation-driven />  
  <mvc:default-servlet-handler/>  
  <context:annotation-config/>  
  <context:component-scan base-package="com" /> 
  <!--Avoid the situation where IE executes AJAX and the returned JSON is downloaded as a file --> 
  <bean id="mappingJacksonHttpMessageConverter" 
    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> 
    <property name="supportedMediaTypes"> 
      <list> 
        <value>text/html;charset=UTF-8</value> 
      </list> 
    </property> 
  </bean> 
  <!-- Enable annotation features of SpringMVC, complete mapping of requests and annotation POJOs --> 
  <bean 
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 
    <property name="messageConverters"> 
      <list> 
        <ref bean="mappingJacksonHttpMessageConverter" /> <!---- JSON converter --> 
      </list> 
    </property> 
  </bean> 
  <!-- Define the prefix and suffix of the file to be redirected, view mode configuration--> 
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
    <!-- My understanding of this configuration is that it automatically adds a prefix and suffix to the string returned by the action method later, making it a usable URL address --> 
    <property name="prefix" value="/backstage/jsp/" /> 
    <property name="suffix" value=".jsp" /> 
  </bean> 
  <!-- Configure file upload, if file upload is not used, it is not necessary to configure, of course, if not configured, then it is not necessary to introduce the upload component package in the configuration file --> 
  <bean id="multipartResolver"  
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
    <!-- Default encoding --> 
    <property name="defaultEncoding" value="utf-8"-8" />  
    <!-- Maximum file size --> 
    <property name="maxUploadSize" value="10485760000" />  
    <!-- Maximum value in memory --> 
    <property name="maxInMemorySize" value="40960" />  
  </bean>  
  <!-- Declare that DispatcherServlet should not intercept the following declared directories  -->  
  <mvc:resources location="/js/" mapping="/js/**" />   
  <mvc:resources location="/images/" mapping="/images/**"/> 
  <mvc:resources location="/css/" mapping="/css/**"/> 
  <mvc:resources location="/common/" mapping="/common/**"/> 
</beans> 

Step 3: JSP Page

<%@ page language="java" pageEncoding="UTF-8"-8"> 
<form action="<%=request.getContextPath()%>/users/add" method="POST" enctype="multipart/form-data"> 
  username: <input type="text" name="username"/><br/> 
  nickname: <input type="text" name="nickname"/><br/> 
  password: <input type="password" name="password"/><br/> 
  yourmail: <input type="text" name="email"/><br/> 
  yourfile: <input type="file" name="myfiles"/><br/>  
  <input type="submit" value="Add New User"/> 
</form> 

Step 4: Spring MVC Controller Code

package com.wlsq.controller; 
import java.io.File; 
import java.io.IOException; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import org.apache.commons.io.FileUtils; 
import org.springframework.beans.factory.annotation.Autowired; 
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; 
import org.springframework.web.servlet.ModelAndView; 
import com.wlsq.model.News; 
import com.wlsq.service.IUserMapperService; 
import com.wlsq.util.Pagination; 
@Controller  
@RequestMapping(value="/users) 
public class UserController { 
  @Autowired 
  private IUserMapperService userService; 
  @RequestMapping(value="/userAll) 
  public ModelAndView searchNews(HttpServletRequest request,HttpServletResponse response){ 
    ModelAndView mv = null; 
    try{ 
      mv = new ModelAndView(); 
      int pageSize = Integer 
          .parseInt(request.getParameter("pageSize") == null ? 0 : Integer.parseInt(request.getParameter("pageSize")))63; "10" 
              : request.getParameter("pageSize")); 
      int pageNum = Integer 
          .parseInt(request.getParameter("pageNum") == null ? "1" 
              : request.getParameter("pageNum")); 
      Map<String, Object> maps = new HashMap<>(); 
      maps.put("pageSize", pageSize); 
      maps.put("pageNum", (pageNum-1) * pageSize); 
      List<News> list =userService.selectAllUsers(maps); 
      int count = userService.selectCountUsers(); 
      Pagination page = new Pagination(count); 
      page.setCurrentPage(pageNum); 
      mv.addObject("pnums", page.getPageNumList()); 
      mv.addObject("currentPage", pageNum); 
      mv.addObject("pnext_flag", page.nextEnable()); 
      mv.addObject("plast_flag", page.lastEnable()); 
      page.lastPage(); 
      mv.addObject("last_page", page.getCurrentPage()); 
      mv.addObject("count", count); 
      mv.addObject("pageCount", page.getPages()); 
      if(list !=null && list.size()>0){ 
        //User exists 
        mv.addObject("partners", list);          
        //Set logical view name, the view resolver will resolve the specific view page according to this name 
        mv.setViewName("/users/users");  
      } else { 
        //User exists 
        mv.addObject("partners", list);          
        //Set logical view name, the view resolver will resolve the specific view page according to this name 
        mv.setViewName("/users/users");  
      } 
    }catch(Exception e){ 
      //Set logical view name, the view resolver will resolve the specific view page according to this name 
      mv.setViewName("/users/users");  
    } 
    return mv; 
  } 
  @RequestMapping(value="/add", method = RequestMethod.POST) 
  public String addUser(@RequestParam MultipartFile[] myfiles, HttpServletRequest request) throws IOException { 
    String username = request.getParameter("username"); 
    String nickname = request.getParameter("nickname"); 
    String password = request.getParameter("password"); 
    String email = request.getParameter("email"); 
    System.out.println("Username:");+username); 
    System.out.println("Nickname:");+nickname); 
    System.out.println("Password:");+password); 
    System.out.println("Email:");+email); 
    //If it is only to upload one file, then only MultipartFile type is needed to receive the file, and it is not necessary to explicitly specify the @RequestParam annotation 
    //If you want to upload multiple files, then here you need to use the MultipartFile[] type to receive the files, and also specify the @RequestParam annotation 
    //And when uploading multiple files, all <input type="file"/> names should all be 'myfiles', otherwise the 'myfiles' in the parameters cannot obtain all uploaded files 
    for (MultipartFile myfile : myfiles) { 
      if (myfile.isEmpty()) { 
        System.out.println("File not uploaded"); 
      } else { 
        System.out.println("File length: "); + myfile.getSize()); 
        System.out.println("File type: "); + myfile.getContentType()); 
        System.out.println("File name: "); + myfile.getName()); 
        System.out.println("Original file name: ")} + myfile.getOriginalFilename()); 
        System.out.println("========================================"); 
        //If you are using the Tomcat server, the file will be uploaded to \\%TOMCAT_HOME%\\webapps\\YourWebProject\\WEB-INF\\upload\\folder 
        String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload"); 
        //There is no need to handle the issue of closing the IO stream here, because the FileUtils.copyInputStreamToFile() method will automatically close the IO stream used internally, and I know this from its source code 
        FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, myfile.getOriginalFilename())); 
      } 
    } 
    return "../../index"; 
  } 
} 

Remember to in WEB-INFO create a directory to store uploaded files (upload)

That's all for this article. I hope it will be helpful to everyone's learning and also hope everyone will support the Yelling Tutorial more.

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal responsibility. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)

You may also like