一、文件上传
文件上传都是通过表单形式提交给后台服务器的,因此,要想实现文件上传功能,就需要提供一个文件上传的表单,该表单需要满足下面的3个条件:
(1)form表单的method属性设置为post;
(2)form表单的enctype属性设置为multipart/from-data;
(3)提供< input type = “file” name = “filename” />的文件上传输入框。
实现文件上传
项目结构
(1)文件上传的依赖
<!--文件上传的依赖-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
(2)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"
metadata-complete="true">
<!--1.配置编码过滤器,在此之前不能获取任何的请求参数,只要获取请求参数,设置编码方式就无用-->
<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>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<!--表示对所有的都进行编码,过滤器的执行顺序是根据<filter-mapping>的顺序执行的-->
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--2.配置HiddenHttpMethodFilter-->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--3.配置SpringMVC的前端控制器-->
<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>
</web-app>
(3)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">
<context:component-scan base-package="com.jd.mvc"/>
<!--配置视图解析器-->
<!--配置视图解析器-->
<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>
<!--配置SpringMVC的视图控制器-->
<mvc:view-controller path="/file" view-name="file"></mvc:view-controller>
<mvc:default-servlet-handler/>
<!--开启SpringMVC的注解驱动-->
<mvc:annotation-driven/>
<!--配置文件上传解析器,将文件封装为MultipartFile-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
</beans>
(4)file.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>测试文件上传和下载</title>
</head>
<body>
<!--1.文件上传-->
<!--enctype属性设置为multipart/form-data,浏览器就会采用二进制流的方式来处理表单数据,服务器就会对文件上传的请求进行解析处理-->
<form th:action="@{/fileUpload}" method="post" enctype="multipart/form-data">
<!--选择文件域-->
头像:<input type="file" name="photo"><br>
<input type="submit" value="上传">
</form>
</body>
</html>
(5)控制器类
FileUploadAndDowController.java
/**
* @author wds
* @date 2021-12-31 16:29
*/
@Controller
public class FileUploadAndDowController {
//文件上传
@RequestMapping("/fileUpload")
public String fileUpload(MultipartFile photo,HttpSession session) throws IOException {
//获取上传文件的文件名
String fileName = photo.getOriginalFilename();
//获取上传文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
//将UUID作为文件名
String uuid = UUID.randomUUID().toString();
//将uuid和suffixName拼接即为最终的文件名
fileName = uuid + suffixName;
ServletContext servletContext = session.getServletContext();
String photoPath = servletContext.getRealPath("photo");
File file = new File(photoPath);
//判断对应的photoPath是否存在
if(!file.exists()){
//弱不存在,则创建目录
file.mkdir();
}
String finalPath = photoPath + File.separator + fileName;
System.out.println(finalPath);
System.out.println("---------------------------------");
//文件上传后的地址
photo.transferTo(new File(finalPath));
System.out.println("-----------------------------------");
return "success";
}
}
二、文件下载
文件下载就是将文件服务器中华的文件下载到本机上。
两个步骤:
(1)在客户端页面使用一个文件下载的超链接,该链接的href属性要指定后台文件下载的方法及文件名(首先要在需要下载的文件目录中添加一个需要下载的文件);
(2)在后台的Controller类中,使用SpringMVC提供的文件下载方法尽心文件下载。SpringMVC提供了一个ResponseEntity类型的对象,使用它可以很方便地定义返回的HttpHeaders对象和HttpStatus对象,通过这两个对象的设置,即可完成下载文件所需要的配置信息。
(1)file.html
<!--2.文件下载-->
<a th:href="@{download}">测试文件下载功能</a>
(2)控制器类
FileUploadAndDowController.java
//文件下载
@RequestMapping("/download")
public ResponseEntity<byte[]> fileDownload(HttpSession session) throws Exception {
//获取ServletContext对象
ServletContext servletContext = session.getServletContext();
//指定要下载的文件所在路径
String path = servletContext.getRealPath("/static/img/未来.jpg");
File file = new File(path);
String fileName=new String(file.getName().getBytes("utf-8"),"iso-8859-1"); //解决中文乱码问题
// //创建输入流
// FileInputStream fis = new FileInputStream(path);
// //创建字节数组,获取当前文件的所有可用长度,不能设置为定长的,否则文件比较大时无法下载
// byte[] bytes = new byte[fis.available()];
// //将流读到字节数组中
// fis.read(bytes);
// //创建HttpHeaders对象设置头信息
// HttpHeaders headers = new HttpHeaders();
// //设置下载方式及下载的名字
// headers.add("Content-Disposition","attachment;filename=未来.jpg");
// //设置响应状态码
// HttpStatus statusCode = HttpStatus.OK;
// //创建ResponseEntity对象
// ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);
// //关闭输入流
// fis.close();
//创建HttpHeaders对象设置头信息
HttpHeaders headers=new HttpHeaders();
//设置下载方式及下载的名字
headers.setContentDispositionFormData("attachment", fileName);// aatachment 附件
headers.setContentType(MediaType.IMAGE_PNG);
//创建ResponseEntity对象
ResponseEntity<byte[]> responseEntity=new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers,HttpStatus.CREATED);
return responseEntity;
}
点击测试文件下载功能即可下载;
选择需要上传的文件,点击上传,即可实现上传。
在控制台的如下位置,可以看到下载的文件的位置。可以查看文件是否下载成功。