在SpringMVC的开发过程中,有时需要实现文档的下载功能。文档的下载功能涉及到了java IO流操作的基础知识,下面本文介绍如何使用java来实现后台文档下载功能。
废话不多说,直接上代码
controller
@ApiOperation("下载")
@RequestMapping("/download")
public void downloadFile(HttpServletRequest request,HttpServletResponse response,String filepath) {
String basePath = request.getSession().getServletContext().getRealPath("/");
ServletOutputStream out = null;
FileInputStream ips = null;
try {
String url = basePath + File.separator + "WEB-INF" + File.separator + filepath;
File file = new File(url);
String filename = file.getName();
ips = new FileInputStream(file);
response.addHeader("Content-Disposition", "attachment; filename=" + new String(filename.getBytes("UTF-8"),"ISO-8859-1"));
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
out = response.getOutputStream();
int len = 0;
byte[] buffer = new byte[1024 * 10];
while ((len = ips.read(buffer)) != -1){
out.write(buffer,0,len);
}
out.flush();
} catch (Exception e){
e.printStackTrace();
}finally {
try {
out.close();
ips.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
前台
<form id="form2" action="${request.contextPath}/checkRecord/download" method="get">
<input id="filepath" name="filepath" type="hidden"/>
</form>
---------------- 以下2行在js文件里面实现 ------------------------------------
$("#filepath").val(传入文件路径);
$("#form2").submit(); 表单提交事件
如有错误,欢迎大家指出,会及时修正