servlet implementation file Download utility class sharing _jsp programming

Source: Internet
Author: User
Tags flush

Copy Code 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 (Downloadfile.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
}
Reading file streams
FIS = new Java.io.FileInputStream (file);
Set the file name of the download save
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 +", in 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 ();
}
catch (IOException e) {
}
}
}
}

public void DoPost (HttpServletRequest 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 ("Out.println ("Out.println ("<title> file Download </title>");
Out.println ("<meta http-equiv=\" content-type\ "content=\" text/html; charset=utf-8\ "/>");
Out.println ("Out.println ("<body>");
Out.print ("This is");
Out.print (This.getclass (). GetName ());
Out.println (", using the" POST method);
Out.println ("</body>");
Out.println ("Out.flush ();
Out.close ();
}

Private String Getbrowser (HttpServletRequest request) {
String useragent = Request.getheader ("User-agent"). toLowerCase ();
if (useragent!= null) {
if (Useragent.indexof ("MSIE") >= 0) {
return "IE";
else if (Useragent.indexof ("Mozilla") >= 0) {
return "FF";
else if (Useragent.indexof ("AppleWebKit") >= 0) {
return "CH";
else if (Useragent.indexof ("Safari") >= 0) {
return "SF";
else if (Useragent.indexof ("opera") >= 0) {
return "OP";
}
}
return null;
}
}

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.