目录
一、使用Spring MVC实现单文件上传
1.加入jar包、依赖
- commons-io-2.4.jar
- commons-fileupload-1.2.2.jar
2.配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!--<url-pattern>*.action</url-pattern>-->
<!-- 使用REST风格-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3.创建springmvc-servlet-.xml
注意:
文件上传的配置:
- MultipartResolver接口:用于处理上传请求,将上传请求包装成可以直接获取文件的数据,方便操作
- CommonsMultipartResolver实现类:使用了Apache的commons-fileupload来完成具体的上传操作
- 默认编码:defaultEncoding;
- 最大文件大小:maxUploadSize
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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.etc.controller"></context:component-scan>
<mvc:annotation-driven/>
<!--配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 文件上传的配置-->
<!-- 处理文件上传-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/><!--默认编码-->
<property name="maxUploadSize" value="-1"/><!--最大文件大小,-1为无限止-->
</bean>
</beans>
4.controller
MultipartFile:
Spring MVC会将上传文件绑定到MultipartFile对象中,并通过该对象完成文件的上传操作
/**
* @author lyt
* 上传文件控制器
*/
@Controller
public class UpLoadController {
Logger logger = Logger.getLogger(UpLoadController.class);
@RequestMapping("/toupload.action")
public String toupload() {
logger.info("进入去上传文件控制器,页面跳转");
return "upload";
}
@RequestMapping("/upload.action")
public String upload(@RequestParam("file") CommonsMultipartFile file, Model model) {
try {
logger.info(file.getOriginalFilename());
//创建路径地址:磁盘路径地址
String path = "D:" + File.separator + "dir" + File.separator + file.getOriginalFilename();
//创建文件
File newFile = new File(path);
//将接收的文件写入目标文件
file.transferTo(newFile);
//将文件的名字,放在作用域中
model.addAttribute("fileName", file.getOriginalFilename());
} catch (IOException e) {
e.printStackTrace();
}
return "main";
}
5.编写文件上传表单页
method="POST"
enctype="multipart/form-data" 指定表单内容类型,支持文件上传
- upmore.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>上传文件</title>
</head>
<body>
<h1>文件上传</h1>
<form action="upload.action" method="post" enctype="multipart/form-data">
<p>文件:<input type="file" name="file"></p>
<p><input type="submit" value="提交"></p>
</form>
</body>
</html>
- main.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>上传文件</title>
</head>
<body>
<h1>上传文件</h1>
<p><img src="http://localhost:8080/dir/${fileName}" width="200px"></p>
</body>
</html>
二、使用Spring MVC实现多文件上传
1.修改controller
file.getOriginalFilename():文件名
@RequestMapping("/touploadmore.action")
public String touploadmore() {
logger.info("多文件上传控制器,页面跳转");
return "uploadmore";
}
@RequestMapping("/uploadmore.action")
public String uploadmore(@RequestParam("file") CommonsMultipartFile[] files, Model model) {
logger.info(files.length);
List<String> list = new ArrayList<>();
for (CommonsMultipartFile file : files) {
if (files.length > 0) {
try {
//创建路径地址:磁盘路径地址
String path = "D:" + File.separator + "dir" + File.separator + file.getOriginalFilename();
//创建文件
File newFile = new File(path);
//将接收的文件写入目标文件
file.transferTo(newFile);
list.add(file.getOriginalFilename());
} catch (Exception e) {
e.printStackTrace();
}
}
}
logger.info(list);
model.addAttribute("list", list);
return "mainmore";
}
2.jsp
- uploadmore.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>文件上传</h1>
<form action="uploadmore.action" method="post" enctype="multipart/form-data">
<p>文件:<input type="file" name="file"></p>
<p>文件:<input type="file" name="file"></p>
<p>文件:<input type="file" name="file"></p>
<p>文件:<input type="file" name="file"></p>
<p>文件:<input type="file" name="file"></p>
<p><input type="submit" value="提交"></p>
</form>
</body>
</html>
- mainmore.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String dirpath = "http://"+request.getServerName()+":"+request.getLocalPort()+"/dir";
request.setAttribute("dp",dirpath);
%>
<html>
<head>
<title>Title</title>
</head>
<body>
<p>文件列表</p>
<c:forEach var="fileName" items="${list}">
<p><a href="${dp}/${fileName}">${fileName}</a></p>
</c:forEach>
</body>
</html>
三、实现用户信息及头像上传
-
controller
User实体类中增加headimg属性
添加控制器
@Controller
public class HeadImgController {
Logger logger = Logger.getLogger(UpLoadController.class);
@RequestMapping("/touploadhead.action")
public String touploadhead() {
logger.info("头像上传控制器,页面跳转");
return "uploadhead";
}
/**
* @param name 姓名
* @param age 年龄
* @param file 头像文件
* @param session 为了让用户信息一直保留在页面当中
* @return
*/
@RequestMapping("/uploadhead.action")
public String uploadhead(String name, String age, @RequestParam("file") CommonsMultipartFile file, HttpSession session) {
try {
logger.info(name);
logger.info(age);
logger.info(file.getOriginalFilename());
//创建路径地址:磁盘路径地址
String path = "D:" + File.separator + "dir" + File.separator + file.getOriginalFilename();
//创建文件
File newFile = new File(path);
//将接收的文件写入目标文件
file.transferTo(newFile);
//创建用户对象
User user = new User(name,age,file.getOriginalFilename());
//将文件放入session作用域中
session.setAttribute("user",user);
} catch (IOException e) {
e.printStackTrace();
}
return "main";
}
}
-
main.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>上传文件</title>
</head>
<body>
<h1>上传文件</h1>
<p>用户姓名:${user.name}</p>
<p>用户年龄:${user.age}</p>
<p><img src="http://localhost:8080/dir/${user.headimg}" width="200px"></p>
</body>
</html>
3. 原文件名与服务器上已有文件重名
覆盖问题 重新定义上传文件名(保证不重名)
- 我们需要在contro中创建一个名字方法
代码如下:
/**
* 防止文件名重复,以致文件被覆盖
* @param name 文件名字
* @return 新的文件名字
*/
private String creatName(String name){
String suffix = name.substring(name.indexOf("."));
//使用随机方法减少重名几率
int n = (int) (Math.random()*1000+1);
String newName = System.currentTimeMillis()+n+suffix;
return newName;
}
@RequestMapping("/uploadmore.action")
public String uploadmore(@RequestParam("file") CommonsMultipartFile[] files, Model model) {
logger.info(files.length);
List<String> list = new ArrayList<>();
for (CommonsMultipartFile file : files) {
if (files.length > 0) {
try {
//调用名字方法
String name = this.creatName( file.getOriginalFilename());
//创建路径地址:磁盘路径地址
String path = "D:" + File.separator + "dir" + File.separator + name/*file.getOriginalFilename()*/;
//创建文件
File newFile = new File(path);
//将接收的文件写入目标文件
file.transferTo(newFile);
list.add(file.getOriginalFilename());
} catch (Exception e) {
e.printStackTrace();
}
}
}
logger.info(list);
model.addAttribute("list", list);
return "mainmore";
}
- 更详细的重定义文件名
private String creatName2(String name2){
//获取文件名,无后缀名
String prefix = name2.substring(0,name2.lastIndexOf("."));
//获取文件后缀名
String suffix = name2.substring(name2.lastIndexOf("."));
String newName2 = prefix+System.currentTimeMillis()+(int) (Math.random()*1000+1)+suffix;
return newName2;
}
- 一个提交按钮中可以提交同时提交多个文件
- Multipart
<h1>文件上传</h1>
<form action="uploadmore.action" method="post" enctype="multipart/form-data">
<p>文件:<input type="file" name="file" multiple></p>
<p>文件:<input type="file" name="file"></p>
<p>文件:<input type="file" name="file"></p>
<p>文件:<input type="file" name="file"></p>
<p>文件:<input type="file" name="file"></p>
<p><input type="submit" value="提交"></p>
</form>