学习笔记——SpringMVC文件上传与下载
2023-01-21
一、文件下载
1、实现文件下载步骤
(1)准备文件下载相关步骤
(2)将ResponseEntity<T>对象,作为方法返回值
(3)为ResponseEntity<T>对象,设置三个参数
2、示例代码
@RequestMapping("/fileDownloadController") public ResponseEntity<byte[]> fileDownload(HttpServletRequest request,String filename){ ResponseEntity<byte[]> responseEntity = null; try { //获取文件位置 //获取文件真实路径【(request|session)->ServletContext】 String realPath = request.getServletContext().getRealPath("/WEB-INF/download/" + filename); //输入流 InputStream is = new FileInputStream(realPath); //文件下载 byte[] bytes = new byte[is.available()]; is.read(bytes); //设置响应头 HttpHeaders headers = new HttpHeaders(); //设置要下载的文件的名字(及文件格式为附件格式,通知服务器下载当前资源,而不是打开) headers.add("Content-Disposition","attachment;filename"); //处理中文文件名问题 headers.setContentDispositionFormData("attachment",new String(filename)); //状态码 responseEntity = new ResponseEntity<>(bytes,headers, HttpStatus.OK); is.close(); } catch (Exception e) { e.printStackTrace(); } return responseEntity; }