1.添加依赖
<!-- 文件上传 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
2.jsp页面开发
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>上传文件</title>
</head>
<body>
<form action="<%=basePath%>/upload" method="post" enctype="multipart/form-data">
上传文件:<input type="file" name="uploadFile">
<input type="submit" value="上传">
</form>
</body>
</html>
3.开发文件上传处理类
@Controller
public class FileController {
//显示文件上传页面
@RequestMapping(value = "/display")
public ModelAndView display(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("items/upload");
return modelAndView;
}
//上传处理
@RequestMapping(value = "/upload")
public ModelAndView upload(@RequestParam("uploadFile")MultipartFile file) throws Exception {
ModelAndView modelAndView = new ModelAndView();
if (!file.isEmpty()) {
//1.取文件格式后缀名
String type = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
//2.取当前时间戳作为文件名
String fileName = System.currentTimeMillis() + type;
//3.设置存放位置
String path = "E:\\代码存档\\springmvc\\springMVC_demo\\src\\main\\java\\com\\steven\\ssm\\upload\\" + fileName;
//4.创建文件
File destFile = new File(path);
try {
//5.复制临时文件到指定目录下
//FileUtils.copyInputStreamToFile()这个方法里对IO进行了自动操作,不需要额外的再去关闭IO流
FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);
} catch (IOException e) {
e.printStackTrace();
}
modelAndView.setViewName("items/success");
} else {
modelAndView.setViewName("items/failed");
}
return modelAndView;
}
}