14.上传文件

 

项目目录结构:

项目依赖包:

FileUploadController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package com.course.controller;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import com.course.util.FileUtil;
import com.course.util.RandomUtil;

@Controller
@RequestMapping("upload")
public class FileUploadController {

// 1.上传单个文件(不修改文件名)
/*
* upload01(MultipartFile testfile)形参名testfile必须与
* 页面表单中<input type="file" name="testfile">元素的name属性值一致
*/
@RequestMapping("upload01")
public String upload01(MultipartFile testfile, HttpServletRequest httpServletRequest) {
System.out.println("upload file = " + testfile);

/*
* 1.获取文件的相关信息
*/
// 文件类型
String contentType = testfile.getContentType();
// 页面表单中<input type="file" name="testfile">元素的name属性值
String formInputElementName = testfile.getName();
// 文件原始文件名
String originalFilename = testfile.getOriginalFilename();
// 文件大小(byte)
long fileSize = testfile.getSize();

System.out.println("contentType = " + contentType);
System.out.println("formInputElementName = " + formInputElementName);
System.out.println("originalFilename = " + originalFilename);
System.out.println("fileSize = " + fileSize + " bytes");

// 2.获取文件上传路径
String fileDir = httpServletRequest.getServletContext().getRealPath("/upload");
System.out.println("fileDir = " + fileDir);
// 3.创建文件对象
File upFile = new File(fileDir, originalFilename);
// 4.把文件流写到目的文件中
try {
testfile.transferTo(upFile);
} catch (IOException e) {
e.printStackTrace();
}

// upload file = org.springframework.web.multipart.commons.CommonsMultipartFile@697a8fff
// contentType = application/octet-stream
// formInputElementName = testfile
// originalFilename = spring-beans-4.3.24.RELEASE.jar
// fileSize = 764406 bytes
// fileDir = E:/Tomcat_8.5/program/apache-tomcat-8.5.60/webapps/08_springmvc_fileupload/upload

return "success";

}

// 2.上传多个文件(不修改文件名)
@RequestMapping("upload02")
public String upload02(MultipartFile[] testfile, HttpServletRequest httpServletRequest) {
if (testfile != null && testfile.length > 0) {
for (int i = 0; i < testfile.length; i++) {
// 1.文件原始文件名
String originalFilename = testfile[i].getOriginalFilename();

// 2.获取文件上传路径
String fileDir = httpServletRequest.getServletContext().getRealPath("/upload");
// 3.创建文件对象
File upFile = new File(fileDir, originalFilename);
// 4.把文件流写到目的文件中
try {
testfile[i].transferTo(upFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}

return "success";

}

/*
* 修改文件名是为了防止文件名相同而覆盖
*/
// 3.上传单个文件(修改文件名)
@RequestMapping("upload03")
public String upload03(MultipartFile testfile, HttpServletRequest httpServletRequest) {
// 1.1 文件原始文件名
String originalFilename = testfile.getOriginalFilename();
// 1.2 获取随机文件名
String randomFileName = RandomUtil.getRandomFileName1(originalFilename);
// 2.获取文件上传路径
String fileDir = httpServletRequest.getServletContext().getRealPath("/upload");
// 3.创建文件对象
File upFile = new File(fileDir, randomFileName);
// 4.把文件流写到目的文件中
try {
testfile.transferTo(upFile);
} catch (IOException e) {
e.printStackTrace();
}

return "success";
}

/*
* 分文件夹管理是为了防止一个目录下的上传文件过多
*/
// 4.上传单个文件(修改文件名,并且分文件夹管理)
@RequestMapping("upload04")
public String upload04(MultipartFile testfile, HttpServletRequest httpServletRequest) {
// 1.1 文件原始文件名
String originalFilename = testfile.getOriginalFilename();
// 1.2 获取随机文件名
String randomFileName = RandomUtil.getRandomFileName1(originalFilename);
// 2.1 获取文件上传路径
String fileDir = httpServletRequest.getServletContext().getRealPath("/upload");
// 2.2 获取根据日期分类的文件夹
String uploadDirByDate = FileUtil.makeUploadDirByDate(fileDir);
// 3.创建文件对象
File upFile = new File(uploadDirByDate, randomFileName);
// 4.把文件流写到目的文件中
try {
testfile.transferTo(upFile);
} catch (IOException e) {
e.printStackTrace();
}

return "success";

}

}

RandomUtil.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package com.course.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

public class RandomUtil {

private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");

private static Random random = new Random();

// 当前时间+ 4位随机数
public static String getRandomFileName1(String originalFileName) {
// 获取文件名类型
int lastDotIndex = originalFileName.lastIndexOf(".");
String suffix = originalFileName.substring(lastDotIndex, originalFileName.length());

// 时间字符串
String timeStr = simpleDateFormat.format(new Date());
// 4位随机数
int randomNum = random.nextInt(9000) + 1000;

String fileName = timeStr + randomNum + suffix;
System.out.println("fileName = " + fileName);
// fileName = 202205082358344585135.jar

return fileName;
}

// uuid
public static String getRandomFileName2(String originalFileName) {
// 获取文件名类型
int lastDotIndex = originalFileName.lastIndexOf(".");
String suffix = originalFileName.substring(lastDotIndex, originalFileName.length());

// 时间字符串
String uuid = UUID.randomUUID().toString().replaceAll("-", "");

String fileName = uuid + suffix;
System.out.println("fileName = " + fileName);
// fileName = 14f2ef3b183b420f9e4d173b6012f2e7.jar

return fileName;
}

// 当前时间毫秒数+ 4位随机数
public static String getRandomFileName3(String originalFileName) {
// 获取文件名类型
int lastDotIndex = originalFileName.lastIndexOf(".");
String suffix = originalFileName.substring(lastDotIndex, originalFileName.length());

// 时间字符串
String time1 = String.valueOf(System.currentTimeMillis());
System.out.println("time1 = " + time1);
String time2 = String.valueOf(new Date().getTime());
System.out.println("time2 = " + time2);
// 4位随机数
String randomNum = String.valueOf(random.nextInt(9000) + 1000);
System.out.println("randomNum = " + randomNum);

String fileName = time1 + randomNum + suffix;
System.out.println("fileName = " + fileName);

/*
* time1 = 1652061343031
* time2 = 1652061343031
* randomNum = 2365
* fileName = 16520613430312365.jar
*/

return fileName;
}

}

FileUtil.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.course.util;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileUtil {


public static String makeUploadDirByDate(String uploadDir) {
// 获取当前系统时间
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
Date date = new Date();
String dateStr = simpleDateFormat.format(date);
String year = dateStr.substring(0, 4);
String month = dateStr.substring(4, 6);
String day = dateStr.substring(6, 8);

String dateDir = year + "/" + month + "/" + day;
File uploadDirByDate = new File(uploadDir, dateDir);
if (!uploadDirByDate.exists()) {
uploadDirByDate.mkdirs();
}

String uploadPath = uploadDirByDate.getAbsolutePath();
return uploadPath;
}

}

log4j.properties

1
2
3
4
5
6
7
8
# Global logging configuration
log4j.rootLogger=INFO, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

springmvc.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">


<!--
配置控制器
包扫描
-->
<context:component-scan base-package="com.course.controller"></context:component-scan>

<!--
合并注解的控制器映射器和控制器适配器的配置
对控制器映射器和控制器适配器进行加强,如把对象转化为json字符串
-->
<mvc:annotation-driven></mvc:annotation-driven>

<!-- 配置文件上传的二进制流的解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 指定文件上传的编码 -->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 指定文件上传的临时目录 -->
<property name="uploadTempDir" value="/upload/temp"></property>
<!-- 指定文件上传的最大大小(byte) -->
<property name="maxUploadSize" value="20971520"></property>
</bean>

<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置前缀 -->
<property name="prefix" value="/WEB-INF/view/"></property>
<!-- 配置后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>

</beans>

web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>01_springmvc_hello</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>

<!-- 配置SpringMVC编码过滤器 -->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<!--
方法1: <url-pattern>*.do</url-pattern>
<url-pattern>/*</url-pattern>
-->
<!-- 指定某个servlet去过滤 -->
<servlet-name>springmvc</servlet-name>
</filter-mapping>

<!-- 配置前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<!-- 加载springmvc.xml -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>

<!-- 启动加载 -->
<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

</web-app>

index.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<h2>1.上传单个文件(不修改文件名)</h2>
<form action="upload/upload01.do" method="post" enctype="multipart/form-data">
选择文件: <input type="file" name="testfile">
<br/>
<input type="submit" value="提交">
</form>

<h2>2.上传多个文件(不修改文件名)</h2>
<form action="upload/upload02.do" method="post" enctype="multipart/form-data">
选择文件1: <input type="file" name="testfile">
<br/>
选择文件2: <input type="file" name="testfile">
<br/>
选择文件3: <input type="file" name="testfile">
<br/>
<input type="submit" value="提交">
</form>

<h2>3.上传单个文件(修改文件名)</h2>
<form action="upload/upload03.do" method="post" enctype="multipart/form-data">
选择文件: <input type="file" name="testfile">
<br/>
<input type="submit" value="提交">
</form>

<h2>4.上传单个文件(修改文件名,并且分文件夹管理)</h2>
<form action="upload/upload04.do" method="post" enctype="multipart/form-data">
选择文件: <input type="file" name="testfile">
<br/>
<input type="submit" value="提交">
</form>

</body>
</html>

success.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>上传成功!</p>
</body>
</html>

浏览器访问: http://localhost:8080/08_springmvc_fileupload/index.jsp