页面代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>文件上传</title>
</head>
<body>
<form method="post" action="/user/up" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上 传 ">
</form>
</body>
</html>
Controller层代码
@RequestMapping("/up")
public void up(HttpServletRequest request,@RequestParam("file") MultipartFile file) throws IOException {
File path = createDir(request.getSession().getServletContext());
String fileName=createName(file.getOriginalFilename());
File f=new File(path, fileName);
System.out.println(f.getAbsoluteFile());
if (!file.isEmpty()){
file.transferTo(f);
}
}
// 创建目录---以日期,一天一个文件夹
private File createDir(ServletContext context) {
String realPath = context.getRealPath("static/upload");
String date = new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
File file = new File(realPath, date);
if (!file.exists()) {
file.mkdir();
}
return file;
}
// 创建文件名--区分同名文件,在文件名前加上当前的时间
private String createName(String name) {
return new SimpleDateFormat("yyyyMMddHHmmssSSS").format(Calendar.getInstance().getTime()) + "_" + name;
}
需要配置SpringMVC
<!--multipartResolver配置 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<property name="maxUploadSize" value="5242880"/>
<property name="uploadTempDir" value="file:/d:/temp"/>
</bean>
需要导入maven依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>