1、项目目录和所需要的依赖
2、文件上传
- 必要前提
1、form表单的enctype取值必须是:multipart/form-data(默认值是:application/x-www-form-urlencoded)
2、method属性必须是:post
3、提供一个文件选择域input type=“file” - 依赖的jar,借助第三方组件。
<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>
3、文件上传的主要代码
1、首先必须要有一个前端的页面,这个待会再说,不是重点。
2、上传的文件都是在request请求中的,这个上传的方法之所以要用post是因为如果用get请求的话,会把文件上传的内容全部放在请求的地址中。如果是post请求的话,会将所有的内容放入到请求体之中。
3、然后我们要获取要放入文件的文件路径。判断这个路径是不是存在的,如果是不存在的,那么就创建一个文件夹。
4、解析request对象,这是一个list集合,在这个集合中还含有其他的普通表单项,所以需要判断是不是文件项。
5、获取文件的名称,然后输入到对应的目录下,删除临时文件。
@Controller
@RequestMapping(path = "con")
public class controller {
@RequestMapping(path = "test")
public String test(HttpServletRequest request) throws Exception {
//使用fileupload组件完成文件上传
//上传的位置
String realPath = request.getSession().getServletContext().getRealPath("/uploads/");
//判断,该路径是否存在
File file = new File(realPath);
if(!file.exists())
file.mkdir();
// 解析request对象,获取上传文件项
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
// 解析request
List<FileItem> items = upload.parseRequest(request);
// 遍历
for(FileItem fileItem:items){
//进行判断,当前item对象是否是上传文件项。
if(!fileItem.isFormField()){
//不是普通表单项
//获取上传文件的名称
String filename = fileItem.getName();
// 完成上传
fileItem.write(new File(realPath,filename));
// 删除临时文件
fileItem.delete();
}
}
return "success";
}
}
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2019/6/30
Time: 0:09
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>文件上传</h3>
<form action="con/test" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload"><br>
<input type="submit" value="上传">
</form>
</body>
</html>
4、项目运行
这里要注意的是,是tomcat文件路径下,不是项目所在目录。
5、项目的源代码
1、pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.springMVC</groupId>
<artifactId>SpringMVC4</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>SpringMVC1 Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<!-- 锁定版本号-->
<spring.version>5.0.2.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<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>
</dependencies>
</project>
2、controller类
package com.spring.controller;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
@Controller
@RequestMapping(path = "con")
public class controller {
@RequestMapping(path = "test")
public String test(HttpServletRequest request) throws Exception {
//使用fileupload组件完成文件上传
//上传的位置
String realPath = request.getSession().getServletContext().getRealPath("/uploads/");
//判断,该路径是否存在
File file = new File(realPath);
if(!file.exists())
file.mkdir();
// 解析request对象,获取上传文件项
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
// 解析request
List<FileItem> items = upload.parseRequest(request);
// 遍历
for(FileItem fileItem:items){
//进行判断,当前item对象是否是上传文件项。
if(!fileItem.isFormField()){
//不是普通表单项
//获取上传文件的名称
String filename = fileItem.getName();
// 完成上传
fileItem.write(new File(realPath,filename));
// 删除临时文件
fileItem.delete();
}
}
return "success";
}
}
3、web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!-- 前端控制器-->
<servlet>
<servlet-name>dispatcherServlet</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>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 解决中文乱码-->
<filter>
<filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
4、index.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2019/6/30
Time: 0:09
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>文件上传</h3>
<form action="con/test" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload"><br>
<input type="submit" value="上传">
</form>
</body>
</html>
5、success.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2019/6/30
Time: 0:08
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<p>success</p>
</body>
</html>
6、SpringMVC.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
">
<context:component-scan base-package="com.spring"></context:component-scan>
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<mvc:resources location="/js/" mapping="/js/**"/>
<mvc:annotation-driven />
<!-- <mvc:resources mapping="/css/**" location="/css/"></mvc:resources>-->
<!-- <mvc:resources mapping="/images/**" location="/images/"></mvc:resources>-->
</beans>