上篇博客讲解了通过springboot+easyui filebox实现文件的上传的功能,这次将实现通过springboot实现单个文件的下载功能。
整个过程分为以下两步:
- 前台定义一个按钮,用于触发下载功能。
- 后台书写具体的文件下载代码
前台代码
HTML按钮代码如下
<td><a href="#button" class="button icon log" onclick="viewOnlineEvidence()">查看学习证明</a></td>
js代码如下:
function viewOnlineEvidence() {
window.location.href="/downloadOnlineLearnMaterials";
}
后台代码
@RequestMapping("/downloadOnlineLearnMaterials")
public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
String fileName = "license_freeware.txt";// 设置文件名,根据业务需要替换成要下载的文件名
if (fileName != null) {
//设置文件路径
String realPath = "E://onlineinfo//";
File file = new File(realPath , fileName);
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;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
System.out.println("success");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return null;
}
演示截图
springboot+easyui filebox文件上传博客链接如下,请多指教