1.在pom.xml文件中添加相关依赖
<!-- file upload-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
- 在springMVC配置文件中注册文件解析器,同时配置springMVC的静态资源视图解析器,防止前端资源被springMVC的前端控制器拦截
注意:文件解析器的id必须为multipartResolver否则会报错
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
<!-- 配置静态资源视图解析器-->
<mvc:resources mapping="/js/**" location="/js/"/>
<!-- 配置文件解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
3.编写前端jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件上传</title>
</head>
<body>
<h3> 文件上传页面</h3>
<form method="post" action="upload/testUpload" enctype="multipart/form-data">
<input type="file" name="upload"> <br>
<input type="submit" value="submit">
</form>
</body>
</html>
5.编写后台Java代码,注意:若使用@RequestParam("upload")注解,则参数需和<input type="file" name="upload">的name属性值一致,若不使用则MultipartFile参数名必须和前端 <input type="file" name="upload">的name属性值一致
package com.chen.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
/**
* @Description:
* @author: chenDing
* @date: 2020/3/6 9:02
*/
@Controller
@RequestMapping("/upload")
public class UploadController {
@RequestMapping("/testUpload") //注意MultipartFile参数名必须和前端 <input type="file" name="upload">的name属性值一致
public String testUpload(HttpServletRequest request, @RequestParam("upload") MultipartFile upload) {
String realPath = request.getSession().getServletContext().getRealPath("/upload");
// String realPath1 = request.getServletContext().getRealPath("/upload");
// System.out.println(realPath);
// System.out.println(realPath1);
File file = new File(realPath);
if (!file.exists()) {
file.mkdirs();
}
String filename = upload.getOriginalFilename();
// System.out.println(upload.getName()); /*表单字段name的值 upload*/
if ("".equals(filename)) {
return "error.jsp";
}
String replace = UUID.randomUUID().toString().replace("-", "");
filename = replace + "_" + filename;
try {
upload.transferTo(new File(realPath,filename));
} catch (IOException e) {
e.printStackTrace();
}
return "success.jsp";
}
}
测试截图