Home Java javaTutorial Detailed explanation of file upload code examples in SpringMVC

Detailed explanation of file upload code examples in SpringMVC

Mar 03, 2017 am 10:22 AM

这是用的是SpringMVC-3.1.1、commons-fileupload-1.2.2和io-2.0.1


首先是web.xml

<?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">  
  <servlet>  
        <servlet-name>upload</servlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        <load-on-startup>1</load-on-startup>  
    </servlet>  
    <servlet-mapping>  
        <servlet-name>upload</servlet-name>  
        <url-pattern>/</url-pattern>  
    </servlet-mapping>  
  
    <filter>  
        <filter-name>SpringCharacterEncodingFilter</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>SpringCharacterEncodingFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  
      
    <welcome-file-list>  
        <welcome-file>/WEB-INF/jsp/user/add.jsp</welcome-file>  
    </welcome-file-list>  
</web-app>
Copy after login

接下来是SpringMVC的配置文件upload-servlet.xml

<?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:mvc="http://www.springframework.org/schema/mvc"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
                        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
                        http://www.springframework.org/schema/mvc  
                        http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd  
                        http://www.springframework.org/schema/context   
                        http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
    <context:component-scan base-package="com.jadyer"/>  
      
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <property name="prefix" value="/WEB-INF/jsp/"/>  
        <property name="suffix" value=".jsp"/>  
    </bean>  
      
    <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->  
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <property name="defaultEncoding" value="UTF-8"/>  
        <!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->  
        <property name="maxUploadSize" value="200000"/>  
    </bean>  
      
    <!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException -->  
    <!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->  
    <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">  
        <property name="exceptionMappings">  
            <props>  
                <!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/jsp/error_fileupload.jsp页面 -->  
                <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop>  
            </props>  
        </property>  
    </bean>  
</beans>
Copy after login

下面是用于上传的表单页面//WEB-INF//jsp//user//add.jsp

<%@ page language="java" pageEncoding="UTF-8"%>  
<form action="<%=request.getContextPath()%>/user/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/>  
    yourfile: <input type="file" name="myfiles"/><br/>  
    yourfile: <input type="file" name="myfiles"/><br/>  
    <input type="submit" value="添加新用户"/>  
</form>
Copy after login

下面是上传成功后打印用户信息的页面//WEB-INF//jsp//user//list.jsp

<%@ page language="java" pageEncoding="UTF-8"%>  
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  
<c:forEach items="${users}" var="user">  
    ${user.value.username}----${user.value.nickname}----${user.value.password}----${user.value.email}  
        <a href="<%=request.getContextPath()%>/user/${user.value.username}">查看</a>  
        <a href="<%=request.getContextPath()%>/user/${user.value.username}/update">编辑</a>  
        <a href="<%=request.getContextPath()%>/user/${user.value.username}/delete">删除</a>  
    <br/>  
</c:forEach>  
<br/>  
<a href="<%=request.getContextPath()%>/user/add">继续添加用户</a>
Copy after login


下面是上传文件内容过大时的提示页面//WEB-INF//jsp//error_fileupload.jsp

<%@ page language="java" pageEncoding="UTF-8"%>  
<h1>文件过大,请重新选择</h1>
Copy after login

接下来是用到的实体类User.Java

package com.jadyer.model;  
  
/** 
 * User 
 * @author 宏宇 
 * @create May 12, 2012 1:24:43 AM 
 */  
public class User {  
    private String username;  
    private String nickname;  
    private String password;  
    private String email;  
    /*==四个属性的getter()、setter()略==*/  
    public User() {}  
    public User(String username, String nickname, String password, String email) {  
        this.username = username;  
        this.nickname = nickname;  
        this.password = password;  
        this.email = email;  
    }  
}
Copy after login


最后是核心的UserController.java

package com.jadyer.controller;  
  
import java.io.File;  
import java.io.IOException;  
import java.util.HashMap;  
import java.util.Map;  
  
import javax.servlet.http.HttpServletRequest;  
  
import org.apache.commons.io.FileUtils;  
import org.springframework.stereotype.Controller;  
import org.springframework.ui.Model;  
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 com.jadyer.model.User;  
  
/** 
 * SpringMVC中的文件上传 
 * @see 第一步:由于SpringMVC使用的是commons-fileupload实现,故将其组件引入项目中 
 * @see       这里用到的是commons-fileupload-1.2.2.jar和commons-io-2.0.1.jar 
 * @see 第二步:在####-servlet.xml中配置MultipartResolver处理器。可在此加入对上传文件的属性限制 
 * @see 第三步:在Controller的方法中添加MultipartFile参数。该参数用于接收表单中file组件的内容 
 * @see 第四步:编写前台表单。注意enctype="multipart/form-data"以及<input type="file" name="****"/> 
 * @author 宏宇 
 * @create May 12, 2012 1:26:21 AM 
 */  
@Controller  
@RequestMapping("/user")  
public class UserController {  
    private final static Map<String,User> users = new HashMap<String,User>();  
      
    //模拟数据源,构造初始数据  
    public UserController(){  
        users.put("张起灵", new User("张起灵", "闷油瓶", "02200059", "menyouping@yeah.net"));  
        users.put("李寻欢", new User("李寻欢", "李探花", "08866659", "lixunhuan@gulong.cn"));  
        users.put("拓拔野", new User("拓拔野", "搜神记", "05577759", "tuobaye@manhuang.cc"));  
        users.put("孙悟空", new User("孙悟空", "美猴王", "03311159", "sunhouzi@xiyouji.zh"));  
    }  
      
    @RequestMapping("/list")  
    public String list(Model model){  
        model.addAttribute("users", users);  
        return "user/list";  
    }  
      
    @RequestMapping(value="/add", method=RequestMethod.GET)  
    public String addUser(){  
        return "user/add";  
    }  
    @RequestMapping(value="/add", method=RequestMethod.POST)  
    public String addUser(User user, @RequestParam MultipartFile[] myfiles, HttpServletRequest request) throws IOException{  
        //如果只是上传一个文件,则只需要MultipartFile类型接收文件即可,而且无需显式指定@RequestParam注解  
        //如果想上传多个文件,那么这里就要用MultipartFile[]类型来接收文件,并且还要指定@RequestParam注解  
        //并且上传多个文件时,前台表单中的所有<input type="file"/>的name都应该是myfiles,否则参数里的myfiles无法获取到所有上传的文件  
        for(MultipartFile myfile : myfiles){  
            if(myfile.isEmpty()){  
                System.out.println("文件未上传");  
            }else{  
                System.out.println("文件长度: " + myfile.getSize());  
                System.out.println("文件类型: " + myfile.getContentType());  
                System.out.println("文件名称: " + myfile.getName());  
                System.out.println("文件原名: " + myfile.getOriginalFilename());  
                System.out.println("========================================");  
                //如果用的是Tomcat服务器,则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\WEB-INF\\upload\\文件夹中  
                String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload");  
                //这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉,我是看它的源码才知道的  
                FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, myfile.getOriginalFilename()));  
            }  
        }  
        users.put(user.getUsername(), user);  
        return "redirect:/user/list";  
    }  
}
Copy after login

补充:记得建立这个目录,用于存放上传的文件,即//WEB-INF//upload//

 以上就是SpringMVC中的文件上传代码实例详解的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Implement file upload and download in Workerman documents Implement file upload and download in Workerman documents Nov 08, 2023 pm 06:02 PM

To implement file upload and download in Workerman documents, specific code examples are required. Introduction: Workerman is a high-performance PHP asynchronous network communication framework that is simple, efficient, and easy to use. In actual development, file uploading and downloading are common functional requirements. This article will introduce how to use the Workerman framework to implement file uploading and downloading, and give specific code examples. 1. File upload: File upload refers to the operation of transferring files on the local computer to the server. The following is used

How to use Laravel to implement file upload and download functions How to use Laravel to implement file upload and download functions Nov 02, 2023 pm 04:36 PM

How to use Laravel to implement file upload and download functions Laravel is a popular PHP Web framework that provides a wealth of functions and tools to make developing Web applications easier and more efficient. One of the commonly used functions is file upload and download. This article will introduce how to use Laravel to implement file upload and download functions, and provide specific code examples. File upload File upload refers to uploading local files to the server for storage. In Laravel we can use file upload

How to solve Java file upload exception (FileUploadException) How to solve Java file upload exception (FileUploadException) Aug 18, 2023 pm 12:11 PM

How to solve Java file upload exception (FileUploadException). One problem that is often encountered in web development is FileUploadException (file upload exception). It may occur due to various reasons such as file size exceeding limit, file format mismatch, or incorrect server configuration. This article describes some ways to solve these problems and provides corresponding code examples. Limit the size of uploaded files In most scenarios, limit the file size

Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

How to use gRPC to implement file upload in Golang? How to use gRPC to implement file upload in Golang? Jun 03, 2024 pm 04:54 PM

How to implement file upload using gRPC? Create supporting service definitions, including request and response messages. On the client, the file to be uploaded is opened and split into chunks, then streamed to the server via a gRPC stream. On the server side, file chunks are received and stored into a file. The server sends a response after the file upload is completed to indicate whether the upload was successful.

File Uploading and Processing in Laravel: Managing User Uploaded Files File Uploading and Processing in Laravel: Managing User Uploaded Files Aug 13, 2023 pm 06:45 PM

File Uploading and Processing in Laravel: Managing User Uploaded Files Introduction: File uploading is a very common functional requirement in modern web applications. In the Laravel framework, file uploading and processing becomes very simple and efficient. This article will introduce how to manage user-uploaded files in Laravel, including verification, storage, processing, and display of file uploads. 1. File upload File upload refers to uploading files from the client to the server. In Laravel, file uploads are very easy to handle. first,

How to implement FTP file upload progress bar using PHP How to implement FTP file upload progress bar using PHP Jul 30, 2023 pm 06:51 PM

How to use PHP to implement FTP file upload progress bar 1. Background introduction In website development, file upload is a common function. For the upload of large files, in order to improve the user experience, we often need to display an upload progress bar to the user to let the user know the file upload process. This article will introduce how to use PHP to implement the FTP file upload progress bar function. 2. The basic idea of ​​implementing the progress bar of FTP file upload. The progress bar of FTP file upload is usually calculated by calculating the size of the uploaded file and the size of the uploaded file.

Simplify file upload processing with Golang functions Simplify file upload processing with Golang functions May 02, 2024 pm 06:45 PM

Answer: Yes, Golang provides functions that simplify file upload processing. Details: The MultipartFile type provides access to file metadata and content. The FormFile function gets a specific file from the form request. The ParseForm and ParseMultipartForm functions are used to parse form data and multipart form data. Using these functions simplifies the file processing process and allows developers to focus on business logic.

See all articles