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