创建maven项目,war包方式
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xx</groupId>
<artifactId>fileUpload</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<spring.version>5.2.8.RELEASE</spring.version>
</properties>
<dependencies>
<!-- 此依赖会关联引用Spring中的所有基础jar包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring-webmvc会依赖spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/taglibs/standard -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.1</version>
</plugin>
</plugins>
</build>
</project>
web.xml
<?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_2_5.xsd" version="2.5">
<display-name>fileUpload</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.
servlet.DispatcherServlet</servlet-class>
<!-- 也可不配置参数,默认加载 /WEB-INF/springmvc-servlet.xml -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
springmvc-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven />
<context:component-scan
base-package="com.xx.ssm.controller" />
<!--必须要有此id名 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--上传文件大小限制,单位:字节 -->
<property name="maxUploadSize" value="5000000"></property>
</bean>
<!--配置的视图解析器对象 -->
<bean id="internalResourceViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!--过滤静态资源 -->
<mvc:resources location="/css/" mapping="/css/**" />
<mvc:resources location="/images/" mapping="/images/**" />
<mvc:resources location="/js/" mapping="/js/**" />
<mvc:resources location="/views/" mapping="/views/**" />
</beans>
创建controller
package com.xx.ssm.controller;
import java.io.File;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class UploadController {
@RequestMapping("/upload")
// 必须要有MultipartFile类型参数。而且参数名必须与表单file控件名一致
public String upload(MultipartFile myFile, HttpServletRequest request) {
// 上传图片存储目录
String path = request.getServletContext().getRealPath("images");
// 获取文件名并使用UUID生成新文件名
String fileName = myFile.getOriginalFilename();
String newFileName = UUID.randomUUID() +
fileName.substring(fileName.lastIndexOf("."));
System.out.println(path + File.separator + newFileName);
// 根据文件的路径+文件名字上传文件
File targetFile = new File(path + File.separator + newFileName);
// 如果找不到指定目录和文件,就新创建此目录和文件
if (!targetFile.exists()) {
targetFile.mkdirs();
}
// 将文件写入硬盘(myFile在内存中)
try {
myFile.transferTo(targetFile);
request.setAttribute("picture", "images\\"+newFileName);
} catch (Exception e) {
e.printStackTrace();
}
return "show";
}
}
index.jsp
<%@ 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>
<form action="upload" method="post" enctype="multipart/form-data">
name:<input type="text" name="name">
file:<input type="file" name="myFile">
<input type="submit" value="提交">
</form>
</body>
</html>
views/show.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<img src="${picture}">
</body>
</html>
项目目录结构

批量文件上传
controller
package com.xx.ssm.controller;
import java.io.File;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class UploadController {
@RequestMapping("/upload")
// 必须要有MultipartFile类型参数。而且参数名必须与表单file控件名一致
public String upload(MultipartFile[] myFiles, HttpServletRequest request) {
// 上传图片服务器存储目录
String path = request.getServletContext().getRealPath("images");
String filePath[] = new String[myFiles.length];
// 获取文件名并使用UUID生成新文件名
for (int i = 0; i < myFiles.length; ++i) {
MultipartFile myFile = myFiles[i];
// 修改文件名
String newFileName = UUID.randomUUID()
+ myFile.getOriginalFilename().substring(myFile.getOriginalFilename().lastIndexOf("."));
// 调用上传方法
upload(path, myFile, newFileName);
filePath[i] = "images\\" + newFileName;
}
request.getSession().setAttribute("pictures", filePath);
return "error";
}
// 上传方法
public String upload(String path, MultipartFile myFile, String newFileName) {
File targetFile = new File(path + File.separator + newFileName);
// 将文件写入服务器路径
try {
myFile.transferTo(targetFile);
// request.setAttribute("picture", "images\\" + newFileName);
return "show";
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
}
或者:
controller
package com.xx.ssm.controller;
import java.io.File;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
@Controller
public class UploadController {
@RequestMapping("/upload")
// 必须要有MultipartFile类型参数。而且参数名必须与表单file控件名一致
public String upload(HttpServletRequest request) {
List<MultipartFile> myFiles = ((MultipartHttpServletRequest) request).getFiles("myFiles");
// 上传图片存储目录
String path = request.getServletContext().getRealPath("images");
String filePath[] = new String[myFiles.size()];
// 获取文件名并使用UUID生成新文件名
for (int i = 0; i < myFiles.size(); ++i) {
MultipartFile myFile = myFiles.get(i);
// 修改文件名
String newFileName = UUID.randomUUID()
+ myFile.getOriginalFilename().substring(myFile.getOriginalFilename().lastIndexOf("."));
filePath[i] = "images\\" + newFileName;
// 调用上传方法
upload(path,myFile,newFileName);
}
request.getSession().setAttribute("pictures", filePath);
return "error";
}
// 上传方法
public String upload(String path, MultipartFile myFile, String newFileName) {
File targetFile = new File(path + File.separator + newFileName);
// 将文件写入服务器路径
try {
myFile.transferTo(targetFile);
return "show";
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
}
对应的index.jsp
<%@ 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>
<form action="upload" method="post" enctype="multipart/form-data">
name:<input type="text" name="name">
file:<input type="file" name="myFiles" >
file:<input type="file" name="myFiles" >
file:<input type="file" name="myFiles" >
<input type="submit" value="提交">
</form>
</body>
</html>
或者index.jsp
<%@ 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>
<form action="upload1" method="post" enctype="multipart/form-data">
name:<input type="text" name="name">
file:<input type="file" name="myFiles" multiple="multiple">
<input type="submit" value="提交">
</form>
</body>
</html>
show.jsp需要引入@taglib依赖
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<c:forEach items="${sessionScope.pictures}" var="picture">
<img src="${picture}" width="100px" height="100px">
</c:forEach>
</body>
</html>
网友评论