一、环境搭建
- 创建一个webapp项目、pom.xml依赖如下
<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>
</dependencies>
- web.xml配置前端控制器
<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>
- 编写基本的springmvc配置文件
<?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.yzx.controller"></context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>
<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>
</beans>
二、代码编写
写一个上传文件的前端表单页面index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件上传</title>
</head>
<body>
<form method="post" action="/upload/u1" enctype="multipart/form-data">
图片:<input type="file" name="uploadFile">
<br><input type="submit" value="上传">
</form>
</body>
</html>
上传成功后跳转的页面success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>上传成功!!!</h1>
</body>
</html>
三、后端代码编写
到这里要在pom里添加上传文件的组件依赖
<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.6</version>
</dependency>
传统方式上传文件
传统方式就是使用servlet方式、直接在控制器方法中加上HttpServletRequest request即可使用原生的servlet完成文件的上传
package com.yzx.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
@RequestMapping("/upload")
public class FileUploadController {
@RequestMapping("/u1")
public String u1(HttpServletRequest request) throws Exception {
System.out.println("文件上传");
String path = request.getSession().getServletContext().getRealPath("/uploads/");
File file = new File(path);
if (!file.exists()){
file.mkdirs();
}
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
List<FileItem> items = servletFileUpload.parseRequest(request);
for (FileItem item : items) {
String filename = item.getName();
item.write(new File(path,filename));
System.out.println(path);
item.delete();
}
return "success";
}
}
运行测试 控制台显示 打开文件夹、发现有刚刚选中的图片 至此文件上传成功
springmvc上传文件
使用springmvc上传文件需要配置在springmvc配置文件中配置文件解析器
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
<property name="maxUploadSize" value="5242880"></property>
</bean>
上传表单uploadfiles.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>springmvc方式上传</h1>
<form method="post" action="/upload/u2" enctype="multipart/form-data">
图片:<input type="file" name="uploadFile">
<br><input type="submit" value="上传">
</form>
</body>
</html>
controller处理代码,需要注意的是参数MultipartFile的参数名一定要与表单的文件项的name相同、否者会报500空指针异常。
@RequestMapping("/u2")
public String u2(HttpServletRequest request, MultipartFile uploadFile) throws Exception {
System.out.println("springmvc跨服务器文件上传");
String path = request.getSession().getServletContext().getRealPath("/uploads/");
File file = new File(path);
if (!file.exists()){
file.mkdirs();
}
String name = uploadFile.getOriginalFilename();
System.out.println(name);
uploadFile.transferTo(new File(path,name));
return "success";
}
测试 查看控制台
查看文件、存在表示上传成功
三、总结
相比传统servlet的上传文件方式、使用springmvc方式除去繁杂的文件解析过程、只要在control的方法参数加上MultipartFile、再在springmvc配置文件中配置文件解析器即可,提高开发效率。
|