一、文件下载
文件下载只能发同步请求,不能发异步请求
1.小文件下载代码模板(以图片为例)
@RequestMapping("")
public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
// 1. 获得文件的真实路径 :
String filePath = session.getServletContext().getRealPath("/static/img");
filePath = filePath + File.separator + "文件名";
// 2. 创建输入流
InputStream inputStream = new FileInputStream(filePath);
// 3. 创建字节数组, 并读取 todo: 为什么要一次读取到内存里面
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes);
// 4. 创建 HttpHeaders 对象设置响应头信息
MultiValueMap<String, String> headers = new HttpHeaders();
// 5. 设置下载方式以及下载文件的名字
headers.add("Content-Disposition", "attachement;filename=1.jpg");
// 6. 设置响应状态码
HttpStatus statusCode = HttpStatus.OK;
// 7. 创建ResponseEndity对象 : 响应体,响应头,响应状态码
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);
// 8. 关闭输入流
inputStream.close();
return responseEntity;
}
2.大文件下载代码模板
@RequestMapping("")
public void fileDownload(HttpServletResponse response) throws IOException {
// 1. 设置响应类型 : 应用程序返回的一个二进制文件, 万能MIME
response.setContentType("application/octet-stream;charset=UTF-8");
// 2. 设置响应头,使浏览器接收到相信信息,直接激活文件下载窗口,即时能打开也不打开
response.setHeader("Content-Disposition", "attachment;filename=studentList.xls");
// 3. 获取输出流 : tomcat 和 浏览器 之间的通道
ServletOutputStream outputStream = response.getOutputStream();
// 4. 读取磁盘的文件, 边读边写
FileInputStream fileInputStream = new FileInputStream("D:\\studentList.xls");
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
byte[] buffer = new byte[1024];
int len = -1;
while((len = bufferedInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
// 5. 关闭资源 : outputStream 交给 tomcat 关闭即可
bufferedInputStream.close();
fileInputStream.close();
outputStream.flush();
}
二、文件上传
文件上传的要求:
1.form表单的请求方式必须为post
2.form表单必须设置属性enctype=“multipart/form-data”
依赖
<!-- 文件上传 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
SpringMVC的配置
<!--
文件上传解析器 :
此类负责将文件类型的数据形成 MultipartFile 参数,其底层依赖 commins-fileupload
-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 设置文件的上传限制大小 -->
<!-- <property name="maxUploadSize" value=""></property>-->
</bean>
代码模板
@RequestMapping(value = "", method = RequestMethod.POST)
public String upload(MultipartFile photo, HttpSession session) throws IOException {
// 获取保存的路径
String filename = photo.getOriginalFilename(); // 获取上传的文件名
//获取上传的文件的后缀名
String hzName = fileName.substring(fileName.lastIndexof(str:"."))
//获取uuid
string uuid = UUID.randomUUID().tostring();
//拼接一个新的文件名I
fileName = uuid + hzName;
//获取ServletContext对象
String saveDir = session.getServletContext().getRealPath("static");
// 目录不存在则创建
File saveDirFile = new File(saveDir);
if(!saveDirFile.exists()) {
saveDirFile.mkdir();
}
// 保存文件
String savePath = saveDir + File.separator + filename;
photo.transferTo(new File(savePath));
// 跳转到成功页面
return "";
}