一、文件上传原理
1、文件上传的必要前提
①form表单的enctype取值必须是:multipart/form-data;
默认值为application/x-www-form-urlencoded,enctype是表单请求正文的类型
②method属性的取值必须是Post;
③提供一个文件选择域<input type="file"/>
2、原理分析
默认application/x-www-form-urlencoded上传的数据全部是键值对的形式,使用multipart/form-data会将表单分开为几个部分;
二、传统方式的文件上传
HelloController类:
package com.zibo.controller;
import org.apache.commons.fileupload.FileItem;
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
public class HelloController {
//设置路径为"/hello"
@RequestMapping(value = "/hello")
public String sayHello(HttpServletRequest request) throws Exception {
//使用fileupload组件来完成文件上传
//指定文件上传的位置
String path = request.getSession().getServletContext().getRealPath("/uploads");
//判断该路径是否存在,若不存在创建该路径
File file = new File(path);
System.out.println(path);
if(!file.exists()){
boolean mkdirs = file.mkdirs();
if (mkdirs){
//解析request对象,获取文件
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
//解析request
List<FileItem> items = upload.parseRequest(request);
//遍历
for (FileItem item : items) {
//判断当前item对象是否是一个上传文件项
if(!item.isFormField()){
//是上传文件项
//获取到上传文件的名称
String itemName = item.getName();
//完成文件上传
item.write(new File(path,itemName));
//删除临时文件
item.delete();
}
}
}
}
//控制台打印"Hello Spring MVC!"
System.out.println("Hello Spring MVC!");
return "success";
}
}
index.jsp页面:
<%--
Created by IntelliJ IDEA.
User: ZiBo
Date: 2020/8/9
Time: 14:52
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>入门程序!</h3>
<h3>文件上传!</h3>
<form action="hello" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload"/><br/>
提交表单:<input type="submit" value="提交表单"/><br/>
</form>
</body>
</html>
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>org.example</groupId>
<artifactId>SpringMVC01</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>SpringMVC01 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.2.8.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>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.11.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.11.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.7</version>
</dependency>
</dependencies>
<build>
<finalName>SpringMVC01</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
运行结果(成功上传):
三、SpringMVC框架文件上传原理分析
备注:
文件解析器代码如下:
<!-- 配置文件解析器,名字必须是multipartResolver-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10495760"/>
</bean>
四、SpringMVC方式的文件上传
HelloController类:
package com.zibo.controller;
import org.apache.commons.fileupload.FileItem;
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 org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
//控制器
@Controller
public class HelloController {
//设置路径为"/hello"
@RequestMapping(value = "/hello")
public String sayHello(HttpServletRequest request, MultipartFile upload) throws Exception {
//使用fileupload组件来完成文件上传
//指定文件上传的位置
String path = request.getSession().getServletContext().getRealPath("/uploads");
//判断该路径是否存在,若不存在创建该路径
File file = new File(path);
System.out.println(path);
if(!file.exists()){
boolean mkdirs = file.mkdirs();
if (mkdirs){
//获取到上传文件的名称
String filename = upload.getOriginalFilename();
//完成文件上传
assert filename != null;
upload.transferTo(new File(path,filename));
}
}
//控制台打印"Hello Spring MVC!"
System.out.println("Hello Spring MVC!");
return "success";
}
}
spring-mvc.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:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/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.zibo.controller"/>
<!-- 视图解析器:解析/WEB-INF/pages/文件夹,后缀为.jsp的页面-->
<!-- 前缀为所在文件夹,后缀为文件类型,使用的时候只需要指定文件名字即可-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 配置文件解析器,名字必须是multipartResolver-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10495760"/>
</bean>
<!-- 指定前端控制器不进行拦截的文件夹,其他如css、images文件夹类似-->
<mvc:resources mapping="/js/**" location="/js/"/>
<!-- 开启SpringMVC注解的支持和自定义类型转换器-->
<mvc:annotation-driven/>
</beans>