共计 11942 个字符,预计需要花费 30 分钟才能阅读完成。
1、文件上传的需求
1.1、注意事项
1.1.1、enctype 取值
enctype 取值必须是:multipart/form-data
1.1.2、method
method 取值必须是:post
1.1.3、file 组件
要有一个 file 组件:
<input type="file"/>
1.2、第三方组件上传
commons-fileupload.jar\commons-io.jar
2、文件上传操作(准备)
2.1、需求
完成在同一服务器中的文件上传,并完成上传后的页面切换。
2.2、新建 maven 项目
通过 maven 创建一个新项目 smvc003
2.3、导包
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.tyschool</groupId>
<artifactId>smvc003</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>smvc003 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.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<spring.version>5.2.2.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</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>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
</dependencies>
<build>
<finalName>smvc003</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>
2.4、配置 springmvc.xml 文件
springmvc.xml
<?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"
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
">
<mvc:annotation-driven />
<!-- 配置扫描器,扫描注解 -->
<context:component-scan base-package="com.tyschool.smvc002"></context:component-scan>
<!-- 配置视图解析器,配置前缀和后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
2.5、配置 web.xml 文件
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>Archetype Created Web Application</display-name>
<!-- 配置 SpringMVC 核心, 前置控制器 DispatcherServlet -->
<servlet>
<servlet-name>SpringMVCDispathcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置初始化参数,用来读取 springmvc.xml 文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springmvc.xml</param-value>
</init-param>
<!-- 配置 servlet 的对象的创建时间点:应用加载时创建。取值只能是非 0 正整数,表示启动顺序 -->
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 前置控制器,映射所有地址 -->
<servlet-mapping>
<servlet-name>SpringMVCDispathcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
2.6、启动服务
启动服务、配置服务
http://localhost:8080/smvc003/index.jsp
3、文件上传操作(开发)
3.1、编写页面
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title> 上传页面 </title>
</head>
<body>
<form action="fileUp" method="post" enctype="multipart/form-data">
名称:<input type="text" name="fname"/><br/>
图片:<input type="file" name="upfile"/><br/>
<input type="submit" value="上传"/>
</form>
</body>
</html>
3.2、加入 servlet.jar
后面我们要接收 HttpServletRequest 对象
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
3.2、编写控制器
FileUpController.java
package com.tyschool.smvc003.controller;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@Controller("fileUpController")
public class FileUpController {@RequestMapping("/fileUp")
public String upFile(String fname, MultipartFile upfile, HttpServletRequest request)throws Exception {// 定义文件名
String fileName = "";
//1. 获取原始文件名
String uploadFileName = upfile.getOriginalFilename();
//2. 截取文件扩展名
String extendName =
uploadFileName.substring(uploadFileName.lastIndexOf(".")+1,
uploadFileName.length());
//3. 把文件加上随机数,防止文件重复
String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
//4. 判断是否输入了文件名
if(!StringUtils.isEmpty(fname)) {fileName = uuid+"_"+fname+"."+extendName; }else {fileName = uuid+"_"+uploadFileName; }
System.out.println(fileName);
//2. 获取文件路径
ServletContext context = request.getServletContext();
String basePath = context.getRealPath("/uploads");
//3. 解决同一文件夹中文件过多问题
String datePath = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
//4. 判断路径是否存在
File file = new File(basePath+"/"+datePath);
if(!file.exists()) {file.mkdirs();
}
//5. 使用 MulitpartFile 接口中方法,把上传的文件写到指定位置
upfile.transferTo(new File(file,fileName));
return "success";
}
}
3.3、配置文件解析器
<!-- 配置文件解析器 -->
<!-- id 的值是固定的 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为 5MB -->
<property name="maxUploadSize"> <value>5242880</value></property>
</bean>
3.4、启动服务完成上传
http://localhost:8080/smvc003/index.jsp
4、文件上传操作(跨服务器上传准备)
4.1、需求
用一个专门的服务器来处理我们上传的文件。将我们的应用程序和上传文件分开为二个服务器。
实际开发中,我们不同的服务器处理不同的业务。比如:
应用服务器:部署项目应用
数据库服务器:运行数据库
nosql 服务器:处理缓存和消息队列
文件服务器:处理图片、声音、视频等各种文件
每个服务器都独立的去完成各自独有的操作。所以,我们在开发的时候,我们就需要将我们的文件上传到不同的服务器。分服务器的目的其实就是为了提高我们项目的管理和执行效率。
4.2、应用逻辑图
4.3、创建服务器端 WEB 项目
4.3.1、创建一个新项目
maven 创建一个新项目 fileuploads
4.3.2、导入对应的 jar 包
<?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.tyschool</groupId>
<artifactId>fileuploads</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>fileuploads 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.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<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.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-client -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.19</version>
</dependency>
</dependencies>
<build>
<finalName>fileuploads</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>
4.3.3、配置 Tomcat 服务器
在 /conf/web.xml 中加入配置
<servlet>
<servlet-name>default</servlet-name>
<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>readonly</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>listings</param-name>
<param-value>false</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
4.3.4、打成 war 包
项目打成 war 包,放入 tomcat
powershell
scp C:\Users\ww\IdeaProjects\smvc003\target\smvc003.war root@192.168.1.123:/usr/local/tomcat/webapps
4.3.5、启动 tomcat
http://192.168.1.123:8080/fileuploads/
5、文件上传操作(跨服务器上传开发)
5.1、编写页面
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title> 上传页面 </title>
</head>
<body>
<form action="fileUp1" method="post" enctype="multipart/form-data">
名称:<input type="text" name="fname"/><br/>
图片:<input type="file" name="upfile"/><br/>
<input type="submit" value="上传"/>
</form>
</body>
</html>
5.2、编写控制器
FileUpTwoController.java
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import java.util.UUID;
@Controller("fileUpTwoController")
public class FileUpTwoController {public static final String FILESERVERURL = "http://192.168.1.123:8080/fileuploads/uploads/";
/**
* 文件上传,保存文件到不同服务器
*/
@RequestMapping("/fileUpload2")
public String testResponseJson(String fname, MultipartFile upfile) throws Exception
{// 定义文件名
String fileName = "";
//1. 获取原始文件名
String uploadFileName = upfile.getOriginalFilename();
//2. 截取文件扩展名
String extendName =
uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1,
uploadFileName.length());
//3. 把文件加上随机数,防止文件重复
String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
//4. 判断是否输入了文件名
if (!StringUtils.isEmpty(fname)) {fileName = uuid + "_" + fname + "." + extendName;
} else {fileName = uuid + "_" + uploadFileName;
}
System.out.println(fileName);
//5. 创建 sun 公司提供的 jersey 包中的 Client 对象
Client client = Client.create();
//6. 指定上传文件的地址,该地址是 web 路径
WebResource resource = client.resource(FILESERVERURL + fileName);
//7. 实现上传
String result = resource.put(String.class, upfile.getBytes());
System.out.println(result);
return "success";
}
}
5.3、启动服务测试
http://localhost:8080/smvc003/index.jsp