ResponseEntity实现文件下载
RequestEntity
可以对request对象进行封装
既可以用原生的request域对象进行处理,也可以先将request域对象封装到RequestEntity中进行操作,其实便捷程度差不多,推荐使用原生servletAPI
ResponseEntity
可以对request对象进行封装
既可以用response对象来对浏览器进行响应,也可以直接创建ResponseEntity对象来响应
原生servletAPI实现文件下载
@RequestMapping("/testDonwServlet/{name}")
@SuppressWarnings("all")
public void testDonwServlet(HttpServletResponse response,@PathVariable("name") String name,HttpSession session) throws IOException {
设置响应头信息
response.setHeader("Content-Disposition","attachment;file="+name+".jpeg");
获取application域对象
ServletContext servletContext = session.getServletContext();
利用当前工程中要下载的静态文件的路径来获取要下载的静态文件在服务器上的路径,也就是在war包中的路径
String realPath = servletContext.getRealPath("/static/"+name+".jpeg");
用realPath创建文件io流fileinputstream
FileInputStream fileInputStream = new FileInputStream(realPath);
将文件io流读到一个字节数组中
byte[] bytes = new byte[fileInputStream.available()];
fileInputStream.read(bytes);
通过ServletOutputStream对象,将字节数组返回给服务器
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(bytes);
}
responseEntity实现文件下载
@RequestMapping("/testDownEntity/{name}")
public ResponseEntity<byte[]> testDownEntity(@PathVariable("name") String name, HttpSession session) throws IOException {
ServletContext servletContext = session.getServletContext();
String realPath = servletContext.getRealPath("/static/"+name+".jpeg");
FileInputStream fileInputStream = new FileInputStream(realPath);
byte[] bytes = new byte[fileInputStream.available()];
fileInputStream.read(bytes);
MultiValueMap<String,String> headers = new HttpHeaders();
headers.add("Content-Disposition","attachment;file="+name+".jpeg");
HttpStatus status = HttpStatus.OK;
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, status);
fileInputStream.close();
return responseEntity;
}
}
原创文章,作者:jamestackk,如若转载,请注明出处:https://blog.ytso.com/268398.html