方式一:通过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;
}
}