@RequestMapping("/downLoadXlsFile")
public ResponseEntity<byte[]> downLoadXlsFile(@RequestParam("filePath")String path,HttpServletRequest request) throws IOException{
String projectPath = request.getSession().getServletContext().getRealPath("");
String xmlsFilePath = projectPath + "portal\\officeFile\\";
File xmlsFile = new File(xmlsFilePath+path);
return buildResponseEntity(xmlsFile);
}
/**
* 构建下载类
* @param file
* @return
* @throws IOException
*/
public static ResponseEntity<byte[]> buildResponseEntity(File file) {
byte[] body = null;
//获取文件
ResponseEntity<byte[]> response=null ;
InputStream is = null;
try {
is = new FileInputStream(file);
body = new byte[is.available()];
is.read(body);
HttpHeaders headers = new HttpHeaders();
//设置文件类型
headers.add("Content-Disposition", "attchement;filename=" + file.getName());
//设置Http状态码
HttpStatus statusCode = HttpStatus.OK;
//返回数据
response = new ResponseEntity<byte[]>(body, headers, statusCode);
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}finally {
if(null != is){
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return response;
}
原文:https://www.cnblogs.com/jagng951014/p/9462597.html