The implementation code for the Struts2 file download function is as follows:
Action file
public class Downloadaction extends Actionsupport {/** * */private static final long Serialversionuid = 58797622317
42395104L; private string filename;//User-requested filename private string inputpath;//The path of the download resource (set in the Struts configuration file) public void Setinputpath (String i
Nputpath) {This.inputpath = InputPath;
Public String Getinputpath () {return inputpath;
public void Setfilename (String fileName) {this.filename = filename;
Public String GetFileName () {return fileName;
Public String DownloadFile () throws Exception {ServletContext context = Servletactioncontext.getservletcontext ();
String Downloaddir = Context.getrealpath ("/upload");
String downloadFile = Context.getrealpath (InputPath);
Prevents users from requesting unsafe resources if (!downloadfile.startswith (Downloaddir)) {return null;
Return to "download_success"; * * * Get input stream resource/public InputStream getInputStream () throws Exception {String path = InputPath + File.separatorchar
+ New String (Filename.getbytes ("iso-8859-1"), "UTF-8"); Return SErvletactioncontext.getservletcontext (). getResourceAsStream (path);
* * * Get the file's default filename when downloading/* public string Getdownloadfilename () {string downloadfilename = filename;
try {downloadfilename = Urlencoder.encode (DownloadFileName, "iso-8859-1");
catch (Unsupportedencodingexception e) {e.getmessage ();
E.printstacktrace ();
return downloadfilename; }
}
JSP file:
<li>
<a href= "<%=path%>/download_downloadaction_downloadfile.action?filename=dwr.jar" > Dwr.jar file under </a>
</li>
<li>
<a href= "<%=path%>/download_downloadaction_ Downloadfile.action?filename=struts2 Tutorial. pdf ">struts2 tutorial. pdf file Under </a>
Struts.xml:
<action name= "download_*_*" class= "Com.wang.action". {1} "method=" {2} ">
<param name=" InputPath ">/upload</param>
<!--result type is set to stream-- >
<result name= "download_success" type= "stream" >
<!--MIME type--> <param name=
" ContentType ">application/octet-stream</param>
<!--inputname value and action gets the input stream resource's method name ( The getInputStream method is defined in the action and the return type is InputStream)-->
<param name= "InputName" >inputStream</param>
<!--setting files with attachments dynamic get file name (Getdownloadfilename method defined in action)-->
<param name= "Contentdisposition" > Attachment;filename= "${downloadfilename}" </param>
<!--set buffer size-->
<param name= " BufferSize ">2048</param>
</result>
The above is a small series to introduce the STRUTS2 implementation of file download function code sharing (filename Chinese transcoding) related content, I hope to help!