Struts2 Download File

Source: Internet
Author: User

When the downloaded file name does not contain Chinese characters, or if the downloaded file does not need to consider the user's permissions issues. Simply make the href attribute of the hyperlink the file name you want to download. Otherwise, it is best to use Struts2 's file download mechanism.

Take the download image as an example

The complete code:

Action

ImportJava.io.File;ImportJava.io.InputStream;ImportOrg.apache.struts2.ServletActionContext;Importcom.opensymphony.xwork2.Action; Public classFiledownloadactionImplementsaction{PrivateString filepath=NULL; PrivateInputStream inputstream=NULL;  Public voidSetFilePath (String filepath) { This. filepath =filepath; }     PublicInputStream GetFile () {returnInputStream; } @Override PublicString Execute ()throwsException {String filename=Servletactioncontext. Getrequest (). GetParameter ("FileName"); InputStream=Servletactioncontext. Getservletcontext (). getResourceAsStream (filepath+File.separator+filename); if(inputstream!=NULL){            returnSUCCESS; }Else {            returnERROR; }    }}

Struts.xml configuration:

< Packagename= "SYXPJ"extends= "Struts-default"namespace= "/SYXPJ">    <Actionname= "Download"class= "Download" >        <resultname= "Success"type= "Stream">            <paramname= "ContentType">Image/jpg</param>            <paramname= "InputName">File</param>            <paramname= "Contentdisposition">Filename= "${request[' filename '}"</param>               <paramname= "BufferSize">1024</param>          </result>    </Action></ Package>

Use:

<href= "${pagecontext.request.contextpath}/syxpj/download.action?filename= Belle.jpg "> data template </a>

Other files only need to change the contenttype parameter of the action's result to the corresponding value.

Struts2 Download File

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.