在做CMS、BBS等系統中,會有發表文章模組,而文章中會有附件和圖片,當點擊附件時可能會出現儲存對話方塊和瀏覽器直接開啟,例如類似這樣的串連:/zlgc/admin/uploadAttach/20110409/20110409145547_708.doc。這種儲存或開啟在不同的瀏覽器表現不一,當然我們也可以統一這種行為,使用J2EE中的filter,過濾每個下載串連,在給每個請求回應response的http添加這是個附件的header,就可以了,核心語句:
<%@ page contentType="application/msword;charset=utf8" %>
<!-- 以上這行設定本網頁為Word格式的網頁 -->
<%
//response.setHeader("Content-disposition","inline; filename=test1.doc"); //線上瀏覽方式,用IE開啟
response.setHeader("Content-disposition","attachment; filename=test1.doc");//下載方式,下載,不用瀏覽器開啟
//以上這行設定傳送到前端瀏覽器時的檔名為test1.doc
//就是靠這一行,讓前端瀏覽器以為接收到一個word文檔
%>
操作步驟:
1、在項目中建立普通的java檔案,作為filter處理體。
2、修改filter,使其實現 javax.servlet.Filter 介面,實現介面中的三個方法 init、doFilter、destroy 。
3、 配置xml,加入filter過濾器。
<filter>
<filter-name>AttachFilter</filter-name>
<filter-class>Servlet.AttachFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AttachFilter</filter-name>
<url-pattern>/admin/uploadAttach/*</url-pattern>
</filter-mapping>
4、重啟tomcat。
注意:filter的執行順序是按xml中順序。
詳細java代碼:
package Servlet;
import java.io.IOException;
import java.util.Date;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AttachFilter implements Filter {
private FilterConfig filterConfig = null;
public void destroy() {
filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest hreq = (HttpServletRequest) request;
HttpServletResponse hresp = (HttpServletResponse) response;
System.out.println(new Date() + " filter");
String url = hreq.getRequestURI();
String fileName = url.substring(url.lastIndexOf('/')+1);//擷取要下載的檔案名稱
System.out.println(hreq.getRequestURI());
System.out.println(fileName);
hresp.setHeader("Content-disposition","attachment; filename="+fileName);
//hresp.addHeader("Content-disposition","attachment; filename="+fileName);
chain.doFilter(hreq, hresp);
}
public void init(FilterConfig arg0) throws ServletException {
this.filterConfig = arg0;
}
}