@RequestMapping("/downloadFile")
public void downloadFile(HttpServletResponse response) {
String downloadFilePath = "D:/ProgramsData/temp/pdfDemo.pdf";//被下载的文件在服务器中的路径,
String fileName = "pdfDemo.pdf";//被下载文件的名称
File file = new File(downloadFilePath);
if (file.exists()) {
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream outputStream = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
outputStream = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
outputStream.write(buffer, 0, i);
i = bis.read(buffer);
}
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
转自:https://blog.csdn.net/xingchen690606313/article/details/82907516