在SpringMVC的文件上传与下载的实现要比在原生的servlet中实现更加容易,配置文件做一些配置就能解决一些功能
1.文件上传
文件上传前端from表单的要求:
1.from表单的请求方式必须为post
2.from表单必须来设置属性enctype=“multipart/form-data”
文件上传配置的要求:
1.需要在pom.xml加入commons-fileupload依赖
2.需要在核心文件中配置文件上传解析器,id为固定的multipartResolver
另外需要注意的是文件上传要解决一个文件重名的问题,解决办法就是获取到上传文件的文件名之后给它换一个不会重复的名字(比如用uuid作为文件名或者时间戳,我这里使用的是uuid)
以下代码是具体的上传和下载的实现(基本可以当做模板使用)
首先是pom.xml中的依赖设置
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<?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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 自动扫描包 -->
<context:component-scan base-package="com.qcw.controller"/>
<!-- 配置Thymeleaf视图解析器 -->
<bean id="viewResolver"
class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
<property name="order" value="1"/>
<property name="characterEncoding" value="UTF-8"/>
<property name="templateEngine">
<bean class="org.thymeleaf.spring5.SpringTemplateEngine">
<property name="templateResolver">
<bean
class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
<!-- 视图前缀 -->
<property name="prefix" value="/WEB-INF/templates/"/>
<!-- 视图后缀 -->
<property name="suffix" value=".html"/>
<property name="templateMode" value="HTML5"/>
<property name="characterEncoding" value="UTF-8" />
</bean>
</property>
</bean>
</property>
</bean>
<!--
配置默认的servlet处理静态资源
-当前工程的web.xml配置的前端控制器DispatcherServlet的url-pattern是/
tomcat的web.xml配置的默认的DefaultServlet的url-pattern也是/
此时,浏览器发送的请求会优先被DispatcherServlet进行处理,但是DispatcherServlet无法处理静态资源
若配置了<mvc:default-servlet-handler/>标签,此时浏览器的所有请求都会被DefaultServlet处理
若配置了<mvc:default-servlet-handler/>和<mvc:annotation-driven/>
浏览器发送的请求会先被DispatcherServlet处理,若无法处理再交给DefaultServlet处理
-->
<mvc:default-servlet-handler/>
<!--开启mvc的注解驱动-->
<mvc:annotation-driven/>
<!--配置视图控制器-->
<mvc:view-controller path="/" view-name="index"></mvc:view-controller>
<!--配置文件上传解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
</beans>
<a th:href="@{/test/down}">下载图片</a>
<form th:action="@{/test/up}" method="post" enctype="multipart/form-data">
头像:<input type="file" name="photo"><br>
<input type="submit" value="上传"><br>
</form>
最后重点controller层的实现
package com.qcw.controller;
/**
* @author wqc
* @date 2022/10/1 9:19
* Description:
* ResponseEntity:可以作为控制器方法的返回值,表示响应到游览器的完整的响应报文
*
* 文件上传的要求
* 1.from表单的请求方式必须为post
* 2.from表单必须来设置属性enctype="multipart/form-data"
*/
@Controller
public class FileUpAndDownController {
@RequestMapping("/test/up")
public String testUp(MultipartFile photo, HttpSession session) throws IOException {
//获取上传文件的文件名
String filename = photo.getOriginalFilename();
//获取上传文件的后缀名
String hzName = filename.substring(filename.lastIndexOf("."));
//获取uuid
String uuid = UUID.randomUUID().toString();
//拼接一个新的文件名
filename = uuid + hzName;
//获取ServletContext对象
ServletContext servletContext = session.getServletContext();
//获取当前工程下photo目录的真实路径
String photoPath = servletContext.getRealPath("/photo");
//创建photoPath所对应的File对象
File file = new File(photoPath);
//判断file所对应的目录是否存在
if (!file.exists()){
file.mkdir();
}
String finalPath = photoPath +File.separator + filename;
//上传文件
photo.transferTo(new File(finalPath));
return "success";
}
@RequestMapping("/test/down")
public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
//获取ServletContext对象
ServletContext servletContext = session.getServletContext();
//获取服务器中文件的真实路径
String realPath = servletContext.getRealPath("/img");
realPath = realPath + File.separator + "1.jpg";
//创建输入流
InputStream is = new FileInputStream(realPath);
//创建字节数组,is.available()获取输入流所对应文件的字节数
byte[] bytes = new byte[is.available()];
//将流读到字节数组中
is.read(bytes);
//创建HttpHeaders对象设置响应头信息
MultiValueMap<String, String> headers = new HttpHeaders();
//设置要下载方式以及下载文件的名字
headers.add("Content-Disposition", "attachment;filename=1.jpg");
//设置响应状态码
HttpStatus statusCode = HttpStatus.OK;
//创建ResponseEntity对象
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);
//关闭输入流
is.close();
return responseEntity;
}
}