在文件下载的时候将其保存而不是直接在浏览器上打开!

来源:互联网 发布:小猪cms创始人陈允 编辑:程序博客网 时间:2024/04/29 03:24

共五个类,分别如下,

package com.netec.util.download;

/**
 * <p>Title:download exception </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2004</p>
 * <p>Company: </p>
 * @author not attributable
 * @version 1.0
 */

public class DowLoadException extends Exception {

  public DowLoadException() {
  }

  public DowLoadException(String p0) {
    super(p0);
  }

  public DowLoadException(Throwable p0) {
    super(p0);
  }

  public DowLoadException(String p0, Throwable p1) {
    super(p0, p1);
  }
}


package com.netec.util.download;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.io.UnsupportedEncodingException;
import java.io.FileInputStream;
import java.io.*;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2004</p>
 * <p>Company: </p>
 * @author not attributable
 * @version 1.0
 */

public class DownLoad {
  private DownLoad() {
  }
  public static void donwload(
      HttpServletRequest request,
      HttpServletResponse response,
      String src_fname,
      String dst_fname
      ) throws DowLoadException {
      int buffSize=1024*10;//size of buffer for read file
      //try {
        //Translates the file's name into application/x-www-form-urlencoded format
       // dst_fname = URLEncoder.encode(dst_fname, "UTF-8");
      //}
     // catch (UnsupportedEncodingException ex) {
      //  throw new DowLoadException("error to encode the file's name ",ex);
      //}
      response.setContentType("application/octet-stream; charset=GBK");
      response.setHeader("Content-disposition", "attachment; filename=/"" + dst_fname + "/"");
      FileInputStream fis = null;
      try {
        fis = new FileInputStream(src_fname);
      }
      catch (FileNotFoundException ex) {
        throw new DowLoadException("source file is not found",ex);
      }
      BufferedInputStream buffIn=new BufferedInputStream(fis);

      byte[] byteBuff=new byte[buffSize];
      try {
        OutputStream outStream = response.getOutputStream();
        BufferedOutputStream buffOut=new BufferedOutputStream(outStream);
        int validLength=0;
        //carry btye arrary
        while((validLength=buffIn.read(byteBuff))!=-1){
          buffOut.write(byteBuff,0,validLength);
        }
        buffOut.flush();
        buffOut.close();
        buffIn.close();
      }
      catch (IOException ex) {
        throw new DowLoadException("file option error",ex);
      }
  }


}
package com.netec.util.download.servlet;

import javax.servlet.*;
import javax.servlet.http.*;

import com.netec.util.RequestNativeProxy;
import com.netec.util.download.DowLoadException;
import com.netec.util.download.DownLoad;

import java.io.*;


public class DownLoadServlet extends HttpServlet {
  private static final String CONTENT_TYPE = "text/html; charset=GBK";

  //Initialize global variables
  public void init() throws ServletException {
  }

  //Process the HTTP Get request
  public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //request proxy deal with "iso-8859-1"cord for getParameter method.
    request=new RequestNativeProxy(request);
    /*
    if(!request.getMethod().trim().equalsIgnoreCase("post")){
     throw new ServletException("This request must be /"post/" method. ");
    }*/
    String src_fname = request.getParameter("src_fname");
    String dst_fname = request.getParameter("dst_fname");
    //To get whole source file name
    src_fname=this.getServletContext().getRealPath(src_fname);
    src_fname = src_fname.replace('/',File.separatorChar);
    try {
      DownLoad.donwload(request, response, src_fname, dst_fname);
    }
    catch (DowLoadException ex) {
      //throw new ServletException(ex);
      ex.printStackTrace(System.out);
    }
    return;
  }

  //Clean up resources
  public void destroy() {
  }
}

package com.netec.util;


public class ConversionHtml {

    /**
     * (Constructor)
     * 
     */
    private ConversionHtml() {
        super();
    }

    public static String StringToHtml(String str) {
        String repStr = str;
        repStr = repStr.replaceAll("/r/n", "<BR>");
        repStr = repStr.replaceAll("/r", "<BR>");
        repStr = repStr.replaceAll("/n", "<BR>");
        repStr = repStr.replaceAll(" ", "&nbsp;");
        return repStr;
    }

    public static String HtmlToString(String str) {
        String repStr = str;
        repStr = repStr.replaceAll("<br>|<BR>|<Br>|<bR>|<br/>|<BR/>", "/r/n");
        repStr = repStr.replaceAll("&nbsp;", " ");
        return repStr;
    }
}
package com.netec.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


public class RequestNativeProxy implements HttpServletRequest {

 
 private HttpServletRequest request;

  
    public RequestNativeProxy(HttpServletRequest request) {
        super();
        this.request=request;
    }

  
    public String getAuthType() {
        return request.getAuthType();
    }

 
    public Cookie[] getCookies() {
        return request.getCookies();
    }

   
    public long getDateHeader(String arg0) {
        return request.getDateHeader(arg0);
    }

   
    public String getHeader(String arg0) {
        return request.getHeader(arg0);
    }

   
    public Enumeration getHeaders(String arg0) {
        return request.getHeaders(arg0);
    }

  
    public Enumeration getHeaderNames() {
        return request.getHeaderNames();
    }

   
    public int getIntHeader(String arg0) {
        return request.getIntHeader(arg0);
    }

  
    public String getMethod() {
        return request.getMethod();
    }

   
    public String getPathInfo() {
        return request.getPathInfo();
    }

  
    public String getPathTranslated() {
        return request.getPathTranslated();
    }

  
    public String getContextPath() {
        return request.getContextPath();
    }

  
    public String getQueryString() {
        return request.getQueryString();
    }

  
    public String getRemoteUser() {
        return request.getRemoteUser();
    }

 
    public boolean isUserInRole(String arg0) {
         return request.isUserInRole(arg0);
    }

  
    public Principal getUserPrincipal() {
        return request.getUserPrincipal();
    }

  
    public String getRequestedSessionId() {
        return request.getRequestedSessionId();
    }

  
    public String getRequestURI() {
        return request.getRequestURI();
    }
  
    public StringBuffer getRequestURL() {
        return request.getRequestURL();
    }

   
    public String getServletPath() {
        return request.getServletPath();
    }

   
    public HttpSession getSession(boolean arg0) {
        return request.getSession(arg0);
    }

   
    public HttpSession getSession() {
        return request.getSession();
    }

  
    public boolean isRequestedSessionIdValid() {
        return request.isRequestedSessionIdValid();
    }

 
    public boolean isRequestedSessionIdFromCookie() {
        return request.isRequestedSessionIdFromCookie();
    }

   
    public boolean isRequestedSessionIdFromURL() {
        return request.isRequestedSessionIdFromURL();
    }

  
    public boolean isRequestedSessionIdFromUrl() {
        throw new UnsupportedOperationException();
    }

  
    public Object getAttribute(String arg0) {
        return request.getAttribute(arg0);
    }

   
    public Enumeration getAttributeNames() {
        return request.getAttributeNames();
    }

  
    public String getCharacterEncoding() {
        return request.getCharacterEncoding();
    }

   
    public void setCharacterEncoding(String arg0)
            throws UnsupportedEncodingException {
        request.setCharacterEncoding(arg0);

    }

   
    public int getContentLength() {
        return request.getContentLength();
    }

   
    public String getContentType() {
        return request.getContentType();
    }

   
    public ServletInputStream getInputStream() throws IOException {
        return request.getInputStream();
    }

   
    public String getParameter(String arg0) {
        try {
            if(request.getParameter(arg0)!=null) {
                return new String(request.getParameter(arg0).getBytes("ISO-8859-1"));
            }else {
                return null;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return "null"+e.getMessage();
        }
    }

  
    public Enumeration getParameterNames() {
        return request.getParameterNames();
    }

   
    public String[] getParameterValues(String arg0) {
        String[] values= request.getParameterValues(arg0);
        for(int i=0;i<values.length;i++) {
            try {
                if(values[i]!=null) {
                    values[i]=new String(values[i].getBytes("ISO-8859-1"));
                }else {
                    values[i]=null;
                }

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                values[i]="null"+e.getMessage();
            }
        }
        return values;
    }

  
    public Map getParameterMap() {
        String newValue;
        String oldValue;
        String name;
        Enumeration names=request.getParameterNames();
        Map parameterMap=request.getParameterMap();
        while(names.hasMoreElements()) {
            name=(String)names.nextElement();
            oldValue=(String)parameterMap.get(name);
            try {
                if(oldValue!=null) {
                    newValue=new String(oldValue.getBytes("ISO-8859-1"));
                }else {
                    newValue=null;
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                newValue="null"+e.getMessage();
            }
            parameterMap.put(name,newValue);
        }
        return parameterMap;
    }

   
    public String getProtocol() {
        return request.getProtocol();
    }

   
    public String getScheme() {
        return request.getScheme();
    }

   
    public String getServerName() {
        return request.getServerName();
    }

  
    public int getServerPort() {
        return request.getServerPort();
    }

   
    public BufferedReader getReader() throws IOException {
        return request.getReader();
    }

  
    public String getRemoteAddr() {
        return request.getRemoteAddr();
    }

  
    public String getRemoteHost() {
        return request.getRemoteHost();
    }

 
    public void setAttribute(String arg0, Object arg1) {
        request.setAttribute(arg0,arg1);
    }

  
    public void removeAttribute(String arg0) {
        request.removeAttribute(arg0);

    }

  
    public Locale getLocale() {
        return request.getLocale();
    }

  
    public Enumeration getLocales() {
        return request.getLocales();
    }

  
    public boolean isSecure() {
        return request.isSecure();
    }

   
    public RequestDispatcher getRequestDispatcher(String arg0) {
        return request.getRequestDispatcher(arg0);
    }

  
    public String getRealPath(String arg0) {
        throw new UnsupportedOperationException();
    }

    public int getRemotePort() {
       
        throw new UnsupportedOperationException();
    }

   
    public String getLocalName() {
        throw new UnsupportedOperationException();
    }

   
    public String getLocalAddr() {
        throw new UnsupportedOperationException();
    }

   
    public int getLocalPort() {
        throw new UnsupportedOperationException();
    }

}
  web.xml 中加如下

       <servlet>
  <servlet-name>download</servlet-name>
  <servlet-class>
   com.netec.util.download.servlet.DownLoadServlet
  </servlet-class>
 </servlet>
 
 <servlet-mapping>
  <servlet-name>download</servlet-name>
  <url-pattern>/download</url-pattern>
 </servlet-mapping>


 jsp页面如下
 <a href="/download?src_fname=XXX.jsp&dst_fname=下载后保存的文件名" />下载</a>

原创粉丝点击