文本文件以及图片在浏览器直接打开解决方法
文本文件以及图片在浏览器直接打开解决办法
项目遇到一个这样一个问题,文件下载的时候,图片、文本文件的附件直接在浏览器里打开了。
文件是存放在apache文件服务器上
解决办法:
文件下载的时候 ,经过一个action处理,在action中重新设置了http头
jsp:
<a href="${ctx }/download/downFiles.action?url=${fileInfoVO.url_down}">下载</a>
action:
/** * 将服务器返回的流文件以附件的形式提供给客户端,以供下载。 * @return */ public String downFiles() { // System.out.println(url); // 文件名 fileName = url.substring(url.lastIndexOf("/") + 1); try { URL urlpath = new URL(url);// 网络URL InputStream is = urlpath.openStream(); HttpServletResponse response = ServletActionContext.getResponse(); // 内嵌显示一个文件(浏览器直接打开) // Content-disposition: inline; // 往response里附加一个文件(提示用户打开或者保存) // Content-disposition: attachment; // 此部分可以在struts配置文件中配置 response.addHeader("Content-Disposition", "attachment; filename=" + fileName); OutputStream out = response.getOutputStream(); int i; while ((i = is.read()) != -1) { out.write(i);// 输出 } out.close(); is.close(); } catch (Exception e) { new BusinessException(e, DownLoadAction.class.getName(), "downFiles"); this.setJsonStream(Common .getUTF8InStream(HttpRespMsg.MSG_COMMON_EXCEPTION)); return "Exception"; } return null; }