文件下载
@RequestMapping("/testDown")
public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
// 先获取servletContext对象
ServletContext servletContext = session.getServletContext();
// 在获取文件的真实路径
String realPath = servletContext.getRealPath("/static/img/1.png");
// 创建输入流
FileInputStream fis = new FileInputStream(realPath);
// new一个byte[],available代表创建数组大小和文件大小相等
byte[] bytes = new byte[fis.available()];
// 将流读到字节数组中
fis.read(bytes);
// 接下来是重点,比较陌生的地方
// 用HttpHeaders对象设置响应头信息
MultiValueMap<String,String> httpHeaders = new HttpHeaders();
// 设置下载方式和下载文件的名字
httpHeaders.add("Content-Disposition", "attachment;filename=1.png");
// 设置响应状态码
HttpStatus statusCode = HttpStatus.OK;
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, httpHeaders, statusCode);
fis.close();
return responseEntity;
}
文件上传
这里和视频里有一点不同
文件上传位置在tomcat的webapps文件夹下对应的项目文件夹里,而视频中是在idea的target文件夹下对应的war包中
注意pom中的依赖
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --
>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
springmvc添加文件解析器
<!--必须通过文件解析器的解析才能将文件转换为MultipartFile对象-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
html中的form标签细节
<form th:action="@{/testUp}" method="post" enctype="multipart/form-data">
图片<input type="file" name="file" /><br/>
<input value="上传" type="submit" />
</form>
控制器代码
@RequestMapping("/testUp")
public String testUp(MultipartFile file,HttpSession session) throws IOException {
// 获取原来的文件名
String filename = file.getOriginalFilename();
// 获取文件后缀
String suffix = filename.substring(filename.lastIndexOf("."));
// 为了避免文件重名,重命名文件
filename = UUID.randomUUID().toString() + suffix;
// 获取服务器中保存图片的路径,如果没有则创建
ServletContext servletContext = session.getServletContext();
String photo = servletContext.getRealPath("photo");
File directory = new File(photo);
// 如果路径不存在则创建之
if(!directory.exists()){
directory.mkdir();
}
String finalPath = photo + File.separator + filename;
// 实现最终上传
file.transferTo(new File(finalPath));
return "success";
}