利用a标签下载文件,向后台传入服务器端的文件地址,后台根据地址获取输入流后,在向前台输出文件流供下载
前台jsp:<a target="blank" href="../bizProblem/downFile.action?path=d:\\wendang.docx&fileid=f3js3sm3j4j3w4skj3k29">测试文档</a>
<span style="white-space:pre"> </span>/** * 根据文件路径下载 * @return */ public String downFile(){ try { String fileName = bizProblemService.selectByFileid(fileid);//根据文件id获取原文件名 HttpServletResponse response = ServletActionContext.getResponse();//获取response //清空一下response对象,否则出现缓存什么的 response.reset(); //指明这是一个下载的respond response.setContentType("application/x-download"); response.setCharacterEncoding("UTF-8"); response.setHeader("Content-type", "text/html;charset=UTF-8"); //<span style="font-family: Arial, Helvetica, sans-serif;">原文件名若为中文,需要转码</span> response.setHeader("Content-Disposition","attachment;filename="+java.net.URLEncoder.encode(fileName, "UTF-8")); ServletOutputStream sos = response.getOutputStream(); BufferedInputStream fin = new BufferedInputStream(new FileInputStream(path)); byte[] content = new byte[1024]; int length; while ((length = fin.read(content, 0, content.length)) != -1) { sos.write(content, 0, length); } fin.close(); sos.flush(); sos.close(); } catch (IOException e) { e.printStackTrace(); } return null;//<span style="font-size:12px;">注意:此处不能返回SUCCESS,<span style="color: rgb(46, 46, 46); font-family: 'microsoft yahei', arial, simsun; line-height: 24px;">每个方法都返回的是一个ActionForward对象,而response是ActionForward对象参数,所以就会使response冲突! 所以处理上传的action返回null就可以了,才不会报错:<span style="color: rgb(51, 51, 51); font-family: Helvetica, Tahoma, Arial, sans-serif; font-size: 14px; line-height: 24px; background-color: rgb(245, 245, 245);">getOutputStream() has already been called for this response</span></span></span> }
关于a标签的说明:若a标签的href挂接的是可直接打开的链接,例如:“../image/test.png"或者“http://192.168.10.10:8080/image/test.png",并且文件为png、jpg等图片格式或者txt文档,则可直接在网页中打开浏览,若文件为docx、xls等文档,则会提供下载操作,不同浏览器对a标签的下载操作有不同的解析,所以下载操作可能不一致