从后端的目录中读出文件,写入HttpServletResponse中
public void downloadFile(String filePath, HttpServletResponse response) {
File file;
FileInputStream in = null;
ServletOutputStream out = null;
try {
String fileName = filePath.substring(filePath.lastIndexOf("/")+1);
response.setHeader("Content-Disposition", "attachment;filename="+fileName);
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
file = ResourceUtils.getFile(filePath);
in = new FileInputStream(file);
out = response.getOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while ((len = in.read(buffer)) != -1) {
out.write(buffer,0,len);
}
}catch (Exception e){
LOGGER.error("下载文件异常!", e);
}finally {
try {
in.close();
out.flush();
out.close();
}catch (Exception e){
LOGGER.error("流关闭异常!");
}
}
}