JSP implementation servlet File download method _jsp programming

Source: Internet
Author: User
Tags flush

This example describes the JSP implementation of the servlet file download method. Share to everyone for your reference. 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 (Downloadfile.class); public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception {long Timestar
    t = 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
      //Read file stream fis = new Java.io.FileInputStream (file);
      Set download saved filename 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 "); else if ("CH". Equals (browser)) {contentdisposition = "attachment;
      Filename= "+ mimeutility.encodetext (showname," UTF8 "," B "); else if ("SF". Equals (browser)) {contentdisposition = "attachment;
      Filename= "+ New String (Showname.getbytes (" UTF-8 ")," iso8859-1 "); else {contentdisposition = "attachment;
      Filename*=utf-8 ' "+ Urlencoder.encode (showname," UTF-8 "). Replace (" + ","%20 ");
      } 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 +", total: "+" (New Date (). GetTime ()-Timestart) + milliseconds.
      ");
    } catch (IOException IoE) {ioe.printstacktrace ();
        Finally {try {if (fis!=null) {fis.close ();
          } catch (IOException e) {} finally {try {if (sos!=null) {sos.close (); The catch (IOException e) {}}} is public void DoPost (HttpServletRequest request, Http
    Servletresponse 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 (" 

I hope this article will help you with your JSP programming.

Related Article

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.