- 创建maven工程,导入依赖
pom.xml
注意:我们在使用maven创建web项目时,千万不要忘记将打包方式改成war
<!--切记不要忘记打成war包-->
<packaging>war</packaging>
<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>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>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.18.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.18.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
2.编写前端测试页面
index.jsp:
注意: 1. form 表单的 enctype 取值必须是: multipart/form-data (默认值是:application/x-www-form-urlencoded),enctype:是表单请求正文的类型
3. method 属性取值必须是 Post,否则不支持
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>测试文件上传</title>
</head>
<body>
<h3>传统文件上传</h3>
<form action="${pageContext.request.contextPath}/user/fileupload1" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload" /><br/>
<input type="submit" value="上传" />
</form>
<h3>Springmvc文件上传</h3>
<form action="${pageContext.request.contextPath}/user/fileupload2" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload" /><br/>
<input type="submit" value="上传" />
</form>
<h3>跨服务器文件上传</h3>
<form action="${pageContext.request.contextPath}/user/fileupload3" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload" /><br/>
<input type="submit" value="上传" />
</form>
</body>
</html>
successs.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>上传文件成功</h3>
</body>
</html>
3.编写springmvc.xml配置文件
注意: 配置文件解析器对象,要求id名称必须是multipartResolver
<?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="cn.xiaozhang.controller"/>
<!--/开启注解扫描end-->
<!--视图解析器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/pages/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
<!--/视图解析器end-->
<!-- 这是springmvc提供的文件解析组件,对上传文件的请求解析等工作进行了封装 -->
<!-- 在测试传统方式上传时,要将该bean注释掉,否则会出现歧义 -->
<!-- 配置文件解析器对象,要求id名称必须是multipartResolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为 1M -->
<property name="maxUploadSize" value="10485760"/>
</bean>
<!--/文件解析器end-->
<!--前端控制器,哪些静态资源不拦截-->
<mvc:resources location="/css/" mapping="/css/**"/>
<mvc:resources location="/images/" mapping="/images/**"/>
<mvc:resources location="/js/" mapping="/js/**"/>
<!--开启mvc注解支持-->
<mvc:annotation-driven/>
</beans>
4.编写Controller页面
http://localhost:8080 应用服务器
http://localhost:9090 图片服务器,存储图片
**注意:**MultipartFile就是对文件的封装,服务器的端口号不能一样
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
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.io.IOException;
import java.util.List;
import java.util.UUID;
@Controller
@RequestMapping("/user")
public class UserController {
/**
* 跨服务器文件上传
* http://localhost:8080 应用服务器
* http://localhost:9090 图片服务器,存储图片
*/
@RequestMapping("/fileupload3")
public String fileuoload3(MultipartFile upload) throws Exception {
System.out.println("跨服务器文件上传...");
// 定义上传文件服务器路径
String path = "http://localhost:9090/uploads/";
// 说明上传文件项
// 获取上传文件的名称
String filename = upload.getOriginalFilename();
// 把文件的名称设置唯一值,uuid
String uuid = UUID.randomUUID().toString().replace("-", "");
filename = uuid+"_"+filename;
// 创建客户端的对象
Client client = Client.create();
// 和图片服务器进行连接
WebResource webResource = client.resource(path + filename);
// 上传文件
webResource.put(upload.getBytes());
return "success";
}
/**
* SpringMVC实现文件上传
* MultipartFile就是对文件的封装。
*/
@RequestMapping("/fileupload2")
public String fileupload2(HttpServletRequest request, MultipartFile upload) throws IOException {
System.out.println("springmvc文件上传...");
// 使用fileupload组件完成文件上传
// 1. 指定文件上传保存的位置
String path = request.getSession().getServletContext().getRealPath("/uploads/");
// 判断该路径是否存在
File file = new File(path);
if (!file.exists() || !file.isDirectory()){
file.mkdirs();
}
// 打印一下文件保存的路径
System.out.println("path:"+path);
// 说明上传文件项
// 2. 获取上传文件的名称
String filename = upload.getOriginalFilename();
// 把文件的名称设置唯一值,uuid
String uuid = UUID.randomUUID().toString().replace("-", "");
filename = uuid+"_"+filename;
// 3.上传文件
upload.transferTo(new File(path,filename));
return "success";
}
/**
* 传统方式上传
*/
@RequestMapping("/fileupload1")
public String fileupload1(HttpServletRequest request) throws Exception {
System.out.println("文件上传.....");
// 使用fileupload组件完成文件上传
// 1. 指定上传的位置
String path = request.getSession().getServletContext().getRealPath("/uploads/");
System.out.println(path);
// 判断该位置是否存在
File file = new File("path:"+path);
if (! file.exists()){
file.mkdirs();
}
// 2. 解析request对象,获取上传文件项
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
// 解析request
List<FileItem> items = upload.parseRequest(request);
System.out.println(items);// length = 0
// 遍历
for (FileItem item : items) {
// 进行判断,当前item对象是否是上传文件项
if(item.isFormField()){
// 说明普通表单
System.out.println("普通表单...");
}else {
// 3. 说明上传文件项
// 获取上传文件的名称
String filename = item.getName();
// 把文件的名称设置唯一值,uuid
String uuid = UUID.randomUUID().toString().replace("-", "");
filename = uuid+"_"+filename;
// 完成上传
item.write(new File(path,filename));
// 删除临时文件
}
}
// 跳转到上传成功页面
return "success";
}
}
5.配置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_3_1.xsd"
version="3.1">
<!--配置核心控制器startt-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<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>
<!--/配置核心控制器end-->
<!--解决中文乱码的过滤器start-->
<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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--/解决中文乱码的过滤器end-->
<!--设置默认首页-->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
启动服务器,进行测试,上传成功!
在这里插入图片描述
传统方式上传注意事项:
在测试传统方式上传时,要将SpringMVC配置文件中的
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为 1M -->
<property name="maxUploadSize" value="10485760"/>
</bean>
注释掉,否则会出现无法成功存储图片的情况,这是因为出现了冲突,无法正确上传的文件造成的。
跨服务器文件上传的注意事项:
存储服务器要是web项目,且发布时要发布带exploded的。
在这里插入图片描述