SpringMvc 文件下载的两种方式
作者:互联网
方式一:通过reponse的输出流
@RequestMapping("/d1")
public ResultVo<String> downloadFile(HttpServletResponse response){
String fileName="test1.png";
try {
//获取response的输出流
ServletOutputStream outputStream = response.getOutputStream();
//读取文件
byte[] bytes = FileUtils.readFileToByteArray(new File("D:\\test.png"));
response.setHeader("Content-Disposition","attachment;filename="+fileName);
//写入到输出流
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
return ResultVoUtil.success("success");
} catch (IOException e) {
return ResultVoUtil.error(e);
}
}
方式二:通过返回ResponseEntity
@GetMapping("/d2")
public ResponseEntity<byte[]> download2(){
//获取文件对象
try {
byte[] bytes = FileUtils.readFileToByteArray(new File("D:\\test2.png"));
HttpHeaders headers=new HttpHeaders();
headers.set("Content-Disposition","attachment;filename=test2.png");
ResponseEntity<byte[]> entity=new ResponseEntity<>(bytes,headers,HttpStatus.OK);
return entity;
} catch (IOException e) {
logger.error("下载出错:",e);
return null;
}
}
标签:文件,outputStream,return,SpringMvc,png,ResponseEntity,new,response,下载 来源: https://blog.csdn.net/qq_28898309/article/details/113969923