Servlet File Download class sharing

Source: Internet
Author: User
Tags log log

Copy codeThe Code is 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 directly opening the target file (for example, in Windows with MS Office suite installed, ie may directly open the doc or xls file you want to download in IE ), add the forced download MIME type to the response header.
*/
Public class DownloadFile extends HttpServlet {
Private static final Log 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 FCM = 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 () + "the file does not exist! ");
Return;
}
// Read the file stream
FS = new java. io. FileInputStream (file );
// Set the file name to download and 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 (FS! = Null ){
Byte [] buff = new byte [1024];
Int bytesRead;
While (-1! = (BytesRead = Fi. read (buff, 0, buff. length ))){
Sos. write (buff, 0, bytesRead );
Sos. flush ();
ByteCount + = bytesRead;
}
}
Sos. flush ();
If (log. isDebugEnabled ()){
Log. debug ("file download completed, file size:" + byteCount + ", total time:" + (new Date (). getTime ()-timeStart) + "millisecond. ");
}
} Catch (IOException ioe ){
Ioe. printStackTrace ();
} Finally {
Try {
If (FS! = Null ){
FCM. 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;
}
}

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.