文件上传和下载
上传
1.设置表单属性
<form action="${pageContext.request.contextPath}/file/fileUpload" method="post" enctype="multipart/form-data">
<input type="file" name="fileName"/>
<button type="submit">提交</button>
</form>
2.springmvc配置文件中添加文件解析器
<!-- 名称必须使用 multipartResolver 因为spring容器使用名称注入 文件上传解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 限制上传文件大小 5M -->
<property name="maxUploadSize" value="5242880"></property>
</bean>
3.使用SpringMvc包装的解析器(CommonsMultipartResolver)进行上传控制,需要引入apache的common-fileupload组件包
添加上传需要的依赖
<!--添加文件上传的依赖-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>

4.为了防止中文乱码,所以需要在web.xml上配置以下信息
<!-- 解决乱码的配置 -->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<!-- 设置request 字符集 -->
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<!-- 设置response 字符集 -->
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

5.控制层方法接收文件
@RequestMapping(value = "fileUpload")
public String fileUpload(MultipartFile fileName) throws Exception{
if (fileName !=null){
//获取文件的名字
String filename = fileName.getOriginalFilename();
//创建一个文件存放的目录
String path = "D:\\file\\";
//判断文件夹是否存在不存在就创建
if(!new File(path).exists()) {
new File(path).mkdirs();
}
//将文件写入设置好的路径
fileName.transferTo(new File(path+filename));
return "UPLOAD SUCCESS!!";
}
return "UPLOAD FAILURE!!";
}

6.界面测试
下载
1.编写控制层
@GetMapping(value = "fileDownload")
public ResponseEntity<byte[]> fileDownload(String fileName) throws Exception{
//文件路径
String path = "D:\\file\\"+fileName;
//需要下载的目录文件
File file = new File(path);
//设置响应头
HttpHeaders headers = new HttpHeaders();
//设置下载的文件的名称 转换文件名的编码
headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName,"UTF-8"));
//读取目标文件为二进制数组
byte[] fileByte = FileCopyUtils.copyToByteArray(file);
//构建ResponseEntity对象
ResponseEntity<byte[]> re = new ResponseEntity<byte[]>(fileByte,headers,HttpStatus.CREATED);
//将对象返回
return re;
}

2.编写前段
<a href="${pageContext.request.contextPath}/file/fileDownload?fileName=demo1.jpg">文件一</a>
<a href="${pageContext.request.contextPath}/file/fileDownload?fileName=demo2.png">文件二</a>

效果如下: