index.jsp 页面:
<input type="button" onclick="javascript:download();" value="点击下载"/> function download(){ var url="<c:out value="${pageContext.request.contextPath}" />/file.do?method=download"; window.open(url); return false ; }
后台action代码:
public void download(HttpServletRequest request, HttpServletResponse response) { try { response.setContentType("application/vnd.ms-excel");//这里指定是excel格式 String path = request.getSession().getServletContext().getRealPath("WEB-INF/download/");//得到上传服务器的路径 path = path+"\"+filename; //这里的文件名称是注入进来的 File file = new File(path); response.reset(); response.setHeader("Content-Disposition", "attachment;fileName="+new String(filename.getBytes("UTF-8"),"iso-8859-1")); InputStream in = new BufferedInputStream(new FileInputStream(file)); byte[] buffer = new byte[in.available()]; in.read(buffer); in.close(); OutputStream out = new BufferedOutputStream(response.getOutputStream()); out.write(buffer); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } //下载文件名称 }