SpringMVC 文件上传 详解

SpringMVC 为文件上传提供直接支持,通过 MultipartResolver 实现

配置 MultipartResolver,在 spring-mvc.xml 文件中
<!-- 文件上传 -->
<bean id="multipartResolver"
         class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
         p:defaultEncoding="UTF-8"
         p:maxUploadSize="104857600"
         p:maxInMemorySize="4096"
         p:uploadTempDir="upload/temp"/>   

在 Controller 中
RequestMapping(value = "/uploadPage")
public String updatePage() {
    return "uploadPage";
}

@RequestMapping(value = "/upload")
public String updateThumb(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) throws Exception {
    if (!file.isEmpty()) {
        file.transferTo(new File("d:/temp/" + file.getOriginalFilename()));// 将上传文件保存到一个目标文件中
        return "redirect:success.html";
    }
    else {
        return "redirect:fail.html";
    }
}

在 uploadPage.jsp 中
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c uri="http://java.sun.com/jsp/jstl/core" %>
<html>
   <head>
      <title>请上传用户头像</title>
   </head>
   <body>
      <h1>请选择上传的头像文件</h1>
      <form method="post" action="<c:url value="/user/upload.html"/>" enctype="multipart/form-data">
         <input type="text" name="name" />
         <input type="file" name="file" />
         <input type="submit" />
      </form>
   </body>
</html>

MultipartFile 常用方法
SpringMVC 文件上传 详解