目录
一、SpringMVC实现文件下载功能
@Controller
public class FileAndDownController {
@RequestMapping("/downFile")
public ResponseEntity<byte[]> getDownFile(HttpSession session) throws IOException {
//获取ServletContext对象
ServletContext servletContext = session.getServletContext();
//获取服务器中文件的真实路径
String realPath = servletContext.getRealPath("/static/img/ya.jpg");
//创建输入流
FileInputStream fileInputStream = new FileInputStream(realPath);
//创建字节数组
byte[] bytes = new byte[fileInputStream.available()];
//将流读取到字节数组中
fileInputStream.read(bytes);
//创建HttpHeaders对象设置响应头信息
HttpHeaders httpHeaders = new HttpHeaders();
//设置要下载方式以及下载文件的名字
httpHeaders.add("Content-Disposition","attachment;filename=ya.jpg");
//设置响应状态码
HttpStatus code = HttpStatus.OK;
//创建ResponseEntity对象
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, httpHeaders, code);
//关闭流
fileInputStream.close();
return responseEntity;
}
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>文件</title>
</head>
<body>
<a th:href="@{/downFile}">下载文件</a>
</body>
</html>
二、SpringMVC实现文件上传功能
文件上传要将form表单中的请求方式为post,并且添加属性enctype="multipart/form-data",SpringMVC中将上传的文件封装到MultipartFile对象中,通过此对象可以获取文件相关信息。
在pom.xml文件中配置并导入jar包
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
@RequestMapping("/UPFile")
public String UPFile(MultipartFile photo,HttpSession session) throws IOException {
//获取上传的文件的文件名
String filename = photo.getOriginalFilename();
//获取上传文件的后缀名
String suffixName = filename.substring(filename.lastIndexOf("."));
//使用UUID作为文件名
String uuid = UUID.randomUUID().toString().replaceAll("_","");
//将uuid与文件后缀名进行拼接
filename = uuid + suffixName;
//获取ServletContext对象,并获取服务器中的photo目录路径
ServletContext servletContext = session.getServletContext();
String path = servletContext.getRealPath("photo");
File file = new File(path);
//判断path对应的路径是否存在
if (!file.exists()){
//目录不存在就创建目录
file.mkdir();
}
String filePath = path + File.separator + filename;
photo.transferTo(new File(filePath));
return "success";
}
在SpringMVC.xml核心配置文件中配置
<!--配置文件上传解析器,将上传的文件封装为MultipartFile-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
前端代码:
<form th:action="@{/UPFile}" method="post" enctype="multipart/form-data">
头像:<input type="file" name="photo"><br>
<input type="submit" value="上传文件">
</form>
实现效果图: