Java File download

Source: Internet
Author: User

File download

Set a hyperlink, can not download it? This is true, but downloading a file over a hyperlink exposes the real address of the downloaded file, which is detrimental to the security of the resource, and by using hyperlinks to download files, the server's files can only be stored in the same directory as the Web application.

The use of program code to download, you can increase security access control, to provide users with authorized authentication to download, you can also provide downloaded data from anywhere, we can be placed in a directory other than the Web application, you can also save the file to the database.

Downloading using the program is also very simple, just set the three header fields as follows:

Content-type:application/x-msdownloadcontent-disposition:attachment;filename= Downloadfilecontent-length:filesize

1, using the program to achieve the download:

 Public classDownactionextendsActionsupportImplementsservletresponseaware{@Override PublicString Execute ()throwsException {String path= "E:\\books\\[struts.2 in depth". Xinxin Sun. Scanned version. pdf ";        Download (path,response); return NULL; }     Public voidDownload (String path,httpservletresponse response) {Try {            //gets the specified file based on pathFile File =NewFile (path); //Get file nameString filename =File.getname (); //set the header of the responseResponse.setcontenttype ("Application/x-msdownload;charset=utf-8"); //set the file name to be displayed in the Save window, if the file name is in Chinese, then set the character set, otherwise garbled. Response.AddHeader ("Content-disposition", "attachment; Filename=" +NewString (Filename.getbytes ("GBK"), "Iso-8859-1")); Response.AddHeader ("Content-length", "" "+file.length ()); //download the file in a streaming fashionInputStream FIS =Newfileinputstream (file); OutputStream Client=Response.getoutputstream (); intlength; byte[] buffer =New byte[1024];  while(length = fis.read (buffer)) > 0){                //Write data to client memoryClient.write (buffer,0, length);            } client.flush ();            Client.close ();        Fis.close (); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }} @Override Public voidSetservletresponse (httpservletresponse response) { This. Response =response; }    Privatehttpservletresponse response;}

2. download files using Struts2

 Public classStrutsdownactionextendsActionsupportImplementsservletresponseaware{PrivateString FileName; PrivateInputStream is;  PublicInputStream getInputStream () {returnis ; }     PublicString GetFileName () {Try {
Solve Chinese garbled response.setheader ("CharSet", "Iso8859-1"); return NewString ( This. Filename.getbytes (), "Iso8859-1"); } Catch(unsupportedencodingexception e) {e.printstacktrace (); return"Get File name Error!"; }} @Override PublicString Execute ()throwsException {File file=NewFile ("E:\\books\\[struts.2 in-depth"). Xinxin Sun. Scan version. pdf "); FileName=File.getname (); is=Newfileinputstream (file); returnSUCCESS; } @Override Public voidSetservletresponse (httpservletresponse response) { This. Response =response; } Privatehttpservletresponse response;}

Struts.xml configuration file

<Actionname= "Sdownload"class= "Org.zsm.action.StrutsDownAction">            <resultname= "Success"type= "Stream">                <paramname= "ContentType">Application/x-msdownload;charset=iso8859-1</param>                <paramname= "InputStream">InputStream</param>                <paramname= "Contentdisposition">Filename=${filename}</param>                <paramname= "BufferSize">2048</param>            </result>        </Action>

Java File download

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.