一、文件上传下载
SpringMVC上下文默认中没有装配MultipartResolver,因此默认情况不能处理文件上传和下载。如果想使用Spring的文件上传功能,则需要在上下文(配置文件)中配置MultipartResolver。
该篇实现了文件的上传下载,主要学习一个思路。
1.项目结构
2.配置文件
pom.xml依赖
需要添加一个文件上传的jar,commons-fileupload,不添加会报错。
顺便把servlet的api(在项目依赖的library中加入tomcat也可以)也添加了。这样就不用在项目library中中添加tomcat了。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!-- 文件上传 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<!-- servlet的api(在项目依赖的library中加入tomcat也可以) -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
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_4_0.xsd"
version="4.0">
<!--配置DispatcherServlet-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--关联一个SpringMVC的配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<!--服务器启动的时候就启动-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<!-- "/"匹配所有的请求不包括.jsp。"/*"匹配所有的请求包括.jsp -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 配置Spring MVC编码过滤器(解决乱码) -->
<filter>
<filter-name>encoding</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>encoding</filter-name>
<!-- "/"匹配所有的请求不包括.jsp。"/*"匹配所有的请求包括.jsp -->
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
springmvc-servlet.xml配置文件。
添加了文件上传。注意:文件上传bean的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
https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 扫描包,让指定包下的注解生效,有IoC容器统一管理 -->
<context:component-scan base-package="com.shengjava.web"/>
<!--开启注解扫描-->
<mvc:annotation-driven/>
<!--在web开发中,我们一般存在静态资源css,js,img。。。-->
<mvc:default-servlet-handler/>
<!--视图解析器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
<!-- 文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 请求的编码格式,必须和jsp的pageEncoding属性一致,以便读取表单内容,默认为ISO-8859-1 -->
<property name="defaultEncoding" value="utf-8"/>
<!-- 上传文件大小上限,单位为字节(10485760=10M) -->
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="1024"/>
</bean>
</beans>
3.jsp页面
index.jsp文件上传页面
注意:表单的method属性需要设置为"post",并且enctype属性要设置为"multipart/form-data"。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="提交">
</form>
<a href="/download">文件下载</a>
</body>
</html>
4.测试
编写测试类,主要是文件上传和下载
CommonsMultipartFile 类是Spring的,用于文件上传。
@Controller
public class FileController {
/**
* 上传文件页面
*/
@GetMapping("/")
public String upload() {
return "index";
}
/**
* 使用spring的文件上传方法(推荐)
*/
@ResponseBody
@PostMapping("/upload")
public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
//设置上传路径
String path = request.getServletContext().getRealPath("/upload");
//如果路径不存在,创建一个
File realPath = new File(path);
if (!realPath.exists()) {
realPath.mkdir();
}
//通过CommonsMultipartFile的方法直接写文件(注意这个时候)
file.transferTo(new File(realPath, file.getOriginalFilename()));
return "success";
}
/**
* 自己写文件上传
*/
@ResponseBody
@PostMapping("/uploadIo")
public String upload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
//获取文件名
String uploadFileName = file.getOriginalFilename();
//如果文件名为空,直接回到首页!
if (uploadFileName == null) {
return "redirect:/";
}
//设置上传路径
String path = request.getServletContext().getRealPath("/upload");
//如果路径不存在,创建一个
File realPath = new File(path);
if (!realPath.exists()) {
realPath.mkdir();
}
//文件输入流
InputStream is = file.getInputStream();
//文件输出流 输出到上传路径下的与该文件名相同的文件中
OutputStream os = new FileOutputStream(new File(realPath, uploadFileName));
//读取写出
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
os.write(bytes, 0, len);
os.flush();
}
os.close();
is.close();
return "success";
}
/**
* 下载文件
*/
@ResponseBody
@GetMapping("/download")
public String fileDownLoad(HttpServletRequest request, HttpServletResponse response) throws Exception {
//要下载的图片地址
String path = request.getServletContext().getRealPath("/upload");
String fileName = "springboot.jpg";
//设置页面不缓存,清空buffer
response.reset();
//字符编码
response.setCharacterEncoding("utf-8");
//二进制传输数据
response.setContentType("multipart/form-data");
//设置响应头
response.setHeader("Content-Disposition",
"attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
File file = new File(path, fileName);
//文件输入流
InputStream is = new FileInputStream(file);
//文件输入流
OutputStream os = response.getOutputStream();
int len = 0;
byte[] bytes = new byte[1024];
while ((len = is.read(bytes)) != -1) {
os.write(bytes, 0, len);
os.flush();
}
is.close();
os.close();
return "";
}
}
访问接口"/“可以进入下载页面,选中文件进行上传,上传成功会返回"success”。
然后返回接口"/",可以点击文件下载。可以下载我们在fileDownLoad()方法中设置的文件地址。
参考自:SpringMVC学习(七)
相关
我的该分类的其他相关文章,请点击:【Spring + Spring MVC + MyBatis】文章目录