前言:最近新上了一个项目,需要文档的上传和下载,之前做这个模块比较少,知识点有些忘记了,这里记录一下,防患于未然。
模板如下:
- 结构预览:
- pom 依赖 : 注意 ==>
servlet 包不要导入 2.x 版本,不支持request.getServletContext()
方法
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
</dependency>
- web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
version="5.0">
<!--配置启动页-->
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
<!--配置 dispatcherServlet 和路径-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!--配置拦截器,防止 post 中文乱码-->
<filter>
<filter-name>characterEncoding</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>characterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
- index.jsp 首页: 上传于下载(success.jsp不贴了)
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%><html>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″>
<body>
<h2>Hello</h2>
<!--enctype="multipart/form-data"支持把部分文件上传包裹图片text文档,excel等-->
<form method="post" action="fileUpload.do" enctype="multipart/form-data">
文件上传: <input type="file" name="file"></br>
文件上传: <input type="file" name="file"></br>
文件上传: <input type="file" name="file"></br>
<button type="submit">提交</button>
</form>
<a href="download.do?fileName=1.txt">下载1.txt</a>
<a href="download/2.txt">2.txt 下载</a>
- spring 总配置文件:applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--导入 mvc 配置文件-->
<import resource="classpath:spring-mvc.xml"/>
</beans>
- spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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">
<!-- 1. 扫描 controller 下所有的组件-->
<context:component-scan base-package="com.bolin.controller"/>
<!-- 2. 开启注解驱动-->
<mvc:annotation-driven/>
<!-- 3. 配置静态资源处理器-->
<mvc:default-servlet-handler/>
<!-- 4. 视图解析器配置-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 5. 使用Spring的commonsMultipartResolver配置MultipartResolver用于文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 6. 设置请求的编码格式, 默认为iso-8859-1 -->
<property name="defaultEncoding" value="utf-8"/>
<!-- 设置允许上传文件的最大值, 单位为 字节 -->
<property name="maxUploadSize" value="5400000"/>
<!-- 设置上传文件的临时路径,看需求加 -->
<property name="uploadTempDir" value="upload/temp"/>
</bean>
</beans>
- controller 配置
@Controller
public class FileUploadController extends HttpServlet {
// 上传文件
@RequestMapping("/fileUpload.do")
public String upload(MultipartFile file[],HttpServletRequest request) throws IOException {
for (int i=0;i<file.length;i++) {
// 1.上传路径
String realPath = request.getServletContext().getRealPath("/upload/");
// 2.获得上传文件名
String name = file[i].getOriginalFilename();
// 3. 改名
int random = new Random().nextInt(999999); // 获取 6 位随机数
if(random<100000){
random+=100000;
}
System.out.println(random);
String newName = new Date().getTime()+random+name;
File file1 = new File(realPath+newName);
file[i].transferTo(file1);
}
return "success";
}
// 下载:
@RequestMapping("/download.do")
public ResponseEntity<byte[]> download(@RequestParam("fileName")String fileName,HttpServletRequest request) throws IOException {
// 1. 获得下载路径
String realPath = request.getServletContext().getRealPath("/download/");
File file = new File(realPath+fileName);
// 2. 转格式
String newName = new String(fileName.getBytes(StandardCharsets.UTF_8), "iso-8859-1");
// 3. 转流
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment",newName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
// 创建状态码 201,CREATED 换成 OK (200)也可以
}
}
- 效果图
去打包好的 war 包里查看 webapps 目录:
upload_war_exploded 文件夹:
下载成功: