@GetMapping("/getDataFile/{id}")
public void getAllData(@PathVariable("id") String id,HttpServletResponse response) {
try {
Object dataFile = service.getDataFile(id);
byte[] byte = dataFile.getByte();
download(byte,dataFile.getFileName(),response);
} catch (RuntimeException e) {
e.printStackTrace();
}
}
public void download(byte[] buffer,String filename, HttpServletResponse response) {
try {
response.reset();
// 设置response的Header 设置后会直接下载文件 而不是预览
// response.addHeader("Content-Length", "" + buf.length);
//response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
//设置文件类型 参考 https://www.runoob.com/http/http-content-type.html
response.setContentType("application/pdf");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
SpringMVC 设置 HttpServletResponse 下载,预览文件
最新推荐文章于 2022-09-03 23:04:17 发布
该代码片段展示了如何使用Spring的@GetMapping注解从指定ID获取数据文件,并通过HttpServletResponse对象将其作为PDF文件提供给客户端下载。方法中包含了错误处理,并设置了响应头以触发文件下载而非预览。
1317

被折叠的 条评论
为什么被折叠?



