servlet to implement file Download utility class sharing

Source: Internet
Author: User
Tags file size flush

 servlet file Download class, in order to prevent the client browser directly open the target file, in the response to join the mandatory download MIME type, we refer to use the bar

  Code as follows: package com;   Import java.io.IOException; Import Java.io.PrintWriter; Import Java.net.URLEncoder; Import Java.util.Date;   Import javax.servlet.ServletException; Import Javax.servlet.http.HttpServlet; Import Javax.servlet.http.HttpServletRequest; Import Javax.servlet.http.HttpServletResponse;   Import Org.apache.commons.logging.Log; Import Org.apache.commons.logging.LogFactory;   Import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeUtility;    /**  * file Download class. To prevent the client browser from opening the destination file directly, such as IE in windows in which the MS Office suite is installed, you may be able to open the doc or xls file you want to download directly in the IE browser, and add the MIME type of the forced download in the response header.  */public class DownloadFile extends HttpServlet { private static final log = Logfactory.getlog (DOWNLOADFI Le.class);    public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception {   Long Timestart = 0;   if (log.isdebugenabled ()) {   timestart=system.currenttimemillis ();  }  Response.setcontenttype ("Application/x-download charset=utf-8");   Java.io.FileInputStream FIS = null;   String filepath = Request.getrealpath ("");   Javax.servlet.ServletOutputStream SOS = null;  //SYSTEM.OUT.PRINTLN ("DownloadFile filename:" + filename);   try {   if (request.getparameter ("filename") ==null      | | Request.getparameter ("ShowName") ==null) {    return;        string filename = Request.getparameter ("filename");    string showname = Request.getparameter ("ShowName");    request.setcharacterencoding ("UTF-8");    response.setcharacterencoding ("UTF-8");    java.io.file File = new Java.io.File (filepath + filename);    if (!file.exists ()) {    Log.error (File.getabsolutepath () + "file does not exist!");     return; &nbs P &NBSP}    //read file stream    fis = new Java.io.FileInputStream (file);    //settings Download the saved file name &nbsP  sos = Response.getoutputstream ();    showname + = filename.substring (Filename.lastindexof ("."));    string contentdisposition = "", browser = getbrowser (request);    if ("IE". Equals (browser)) {    contentdisposition = "attachment; Filename= "+ urlencoder.encode (showname," UTF-8 "). Replace (" + ","%20 ");   &NBSP} else if ("CH". Equals (browser)) {    contentdisposition = "attachment; Filename= "+ mimeutility.encodetext (showname," UTF8 "," B ");   &NBSP} else if ("SF". Equals (browser)) {    contentdisposition = "attachment; Filename= "+ New String (Showname.getbytes (" UTF-8 ")," iso8859-1 ");   &NBSP} else {    contentdisposition = "attachment; Filename*=utf-8 ' "+ Urlencoder.encode (showname," UTF-8 "). Replace (" + ","%20 ");   &nbsp    response.setheader ("Content-disposition", contentdisposition);    int byteCount = 0;     if (FIS!= null) {    byte[]Buff = new byte[1024];     int bytesread;     while ( -1!= (bytesread = fis.read (buff, 0, buff.length)) {     sos.write (buff, 0, Bytesread );      sos.flush ();      bytecount + = Bytesread;    }         sos.flush ();    if (log.isdebugenabled ()) {    log.debug ("File download complete, File size: + ByteCount +", in total: "+" (New Date (). GetTime ()-Timestart) + "Ms. ");   &NBSP}  } catch (IOException IoE) {   ioe.printstacktrace ();  } finally {   try {     if (fis!=null) {     fis.close ();    }   &nbsp} catch (IOException e) {&nbs P &NBSP} finally {    try {     if (sos!=null) {      sos.close ();     & nbsp;}    } catch (IOException e) {   }   &nbsp}  } &nbsp}    public void DoPost (Ht Tpservletrequest request, HttpservletrespOnse response) throws Servletexception, IOException {  Response.setcontenttype ("text/html");   PrintWriter out = Response.getwriter ();   OUT.PRINTLN ("<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">");   OUT.PRINTLN ("<html>");   OUT.PRINTLN ("<head>");   OUT.PRINTLN ("  <title> file Download </title>");   OUT.PRINTLN ("  <meta http-equiv=" Content-type "content=" text/html; Charset=utf-8 "/>");   OUT.PRINTLN ("</head>");   OUT.PRINTLN ("<body>");   Out.print ("This is");   Out.print (This.getclass (). GetName ());   OUT.PRINTLN (", using the" POST method);   OUT.PRINTLN ("</body>");   OUT.PRINTLN ("</html>");   Out.flush ();   Out.close (); &NBSP}    private string getbrowser (HttpServletRequest request) {  String useragent = Request.getheader ( "User-agent"). toLowerCase ();   if (useragent!= null) {   IF (Useragent.indexof ("MSIE") >= 0) {    return "IE";   &N BSP;} else if (Useragent.indexof ("Mozilla") >= 0 {    return "FF";    } else if ("Useragent.indexof" ("app Lewebkit ") >= 0 {    return" CH ";   &nbsp} else if (Useragent.indexof (" Safari ") >= 0) {  &NB Sp return "SF";   &NBSP} else if (Useragent.indexof ("opera") >= 0) {    return "OP";    }  }   RE Turn null; &NBSP}}    

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.