SprigMvc文件下载

发布时间 2023-11-10 14:21:15作者: 方毅
@RequestMapping(method = RequestMethod.GET ,value = "/down")
public ResponseEntity<byte[]> DownLoad(HttpServletRequest request,String filename ){

// 获取文件的真实路径
String realPath = request.getServletContext().getRealPath("/WEB-INF/download/" + filename);
HttpHeaders httpHeaders ;
byte[] file ;
try {
InputStream inputStream=new FileInputStream(realPath);
try {
httpHeaders=new HttpHeaders();
file =new byte[inputStream.available()];
inputStream.read(file);
httpHeaders.add("Content-Disposition","attachment;filename="+filename);
httpHeaders.setContentDispositionFormData("Content-Disposition", URLEncoder.encode(filename, "utf-8"));
} catch (IOException e) {
throw new RuntimeException(e);
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}

//需要传入的三个参数 文件名 文件的的字节读入数组 文件的请求头 文件的状态
ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(file, httpHeaders, HttpStatus.OK);
return responseEntity;

}