Java server file download via hyperlinks and servlet configuration

Source: Internet
Author: User

1, on the page we can simply write:

2. Configure the servlet to jump to the Java class in Web. xml:

  <servlet>    <Servlet-name>Bbsfile</Servlet-name>    <Servlet-class>Com.zl.common.downloadfile</Servlet-class>  </servlet>  <servlet-mapping>    <Servlet-name>Bbsfile</Servlet-name>    <Url-pattern>/bbsfile</Url-pattern>  </servlet-mapping>

3. Write the Java class to download the file:

/** Created on 2004-12-22 * * TODO to change the template for this generated file go to * Window-preferences-java -Code Style-code Templates*/ PackageCom.zl.common;ImportJava.io.BufferedInputStream;ImportJava.io.BufferedOutputStream;ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.IOException;ImportJavax.activation.FileTypeMap;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportCom.cd.util.ReadPropertiesFile;Importcom.zl.base.core.Constants; Public classDownloadFileextendsHttpServlet {/**     *      */    Private Static Final LongSerialversionuid = 1L; /*** Default constructor. */     PublicDownloadFile () {Super(); }    /*** Init method. *      * @throwsservletexception * never. */     Public voidInit ()throwsservletexception {return; }     Public voidService (HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException {Service (Request, response,true); }     Public voidService (HttpServletRequest request, httpservletresponse response,BooleanBlnsyn)throwsservletexception, IOException {Try{Object User=request.getsession (). getattribute (Constants.session_user); if(User! =NULL) {String MimeType= Request.getparameter ("MimeType"); String filename= Request.getparameter ("filename"); String Oldfilename= Request.getparameter ("Saveasfilename"); if(mimetype!=NULL) Response.setcontenttype (MimeType); if(Oldfilename = =NULL) {Response.setheader ("Content-disposition", "attachment; Filename= "+filename); } Else{oldfilename=NewString (Oldfilename.getbytes ("iso-8859-1"), "UTF-8");; Response.setheader ("Content-disposition", "attachment; Filename= "+oldfilename); //Response.setheader ("content-disposition", "attachment; //filename= "+oldfilename);} String Uploadfilepath= Readpropertiesfile.getinstance (). GetProperty ("Uploadfilepath", "c:/") + "announce/"; File File=NewFile (Uploadfilepath +filename); System.out.println ("File path:" +uploadfilepath +filename); if(!file.exists ())                {File.createnewfile (); } filetypemap FMap=Filetypemap.getdefaultfiletypemap (); String filetype=fmap.getcontenttype (file);                Response.setcontenttype (filetype); Response.setcontentlength ((int) file.length ()); Bufferedoutputstream Bos=NewBufferedoutputstream (Response.getoutputstream ()); Bufferedinputstream bis=NewBufferedinputstream (Newfileinputstream (file)); byte[] input =New byte[1024]; BooleanEOF =false;  while(!EOF) {                    intLength =bis.read (input); if(length = =-1) {EOF=true; } Else{bos.write (input,0, length);                }} bos.flush ();                Bis.close ();            Bos.close (); }        } Catch(Exception ex) {}return; }    }

Where the Readpropertiesfile class is a way to define where files are saved:

 PackageCom.cd.util;ImportJava.io.InputStream;Importjava.util.Properties;/*** Read the contents of the sale.properties file * *@authorlxk 2013-05-28 Single case **/ Public classReadpropertiesfile {Static PrivateReadpropertiesfile instance =NewReadpropertiesfile ();//Unique Instances    PrivateProperties Dbprops =NULL; PrivateProperties Getdbprops () {returnDbprops; }    //Default Private construction method    PrivateReadpropertiesfile () {InputStream is= Readpropertiesfile.class. getResourceAsStream ("/sale.properties"); Dbprops=NewProperties (); Try{dbprops.load (IS); } Catch(Exception e) {System.err.println ("Cannot read the properties file. Make sure that sale.properties is in the path specified in Classpath "); }    }    /*** Returns a unique instance. If this method is called for the first time, the instance is created *@returnDbconnectionmanager only Instance*/     Public Static synchronizedreadpropertiesfile getinstance () {if(Instance = =NULL) {instance=NewReadpropertiesfile (); }        returninstance; }     Publicstring GetProperty (String key, String defaultvalue) {//If Taglib.properties does not have a key, the default DefaultValue        returninstance.getdbprops (). GetProperty (key, DefaultValue); }}

Write a sale.properties file that configures the path of the server file to be stored in the project:

# #uploadfilepath =/home/webapp/sxwl_file/upload/
uploadfilepath=c:/logs/

Java server file download via hyperlinks and servlet configuration

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.