1. JSP page Hyperlink <a href= "javascript:void (0)" onclick= "DownloadFile (' ${id} ')" >${name}</a>
2. Form submission
<form action= "downloadfile.html" id= "Downloadfileform" "method=" Post "enctype=" Multipart/form-data "target=" Downloadfileiframe ">
<input type= "hidden" id= "Downloadfileid" name= "id"/>
<iframe name= "Downloadfileiframe" style= "Display:none" ></iframe>
</form>
<script type= "Text/javascript" >
function DownloadFile (ID) {
$ ("#downloadFileId"). Val (id);
Downloadfileform.submit ();
}
</SCRIPT>
3. Struts2.xml
<action name= "DownloadFile" class= "cn.shaviation.frm.webapp.action.FileUploadAction" method= "Download" >
<result name= "Success" type= "Stream" >
<param name= "ContentType" >${sysfile.type}</param>
<param name= "InputName" >inputStream</param>
<param name= "BufferSize" >40960</param>
</result>
<result name= "Input" >/WEB-INF/pages/common/downloadFileErrorMessage.jsp</result>
</action>
4. The download method in Fileuploadaction
Public String Download () {//download file
try {
Sysfile = Sysfilemanager.get (ID);
InputStream = new FileInputStream (Sysfile.getpath ());
GetResponse (). SetHeader ("Content-disposition", "attachment; Filename=" + Urlencoder.encode (Sysfile.getName (), " UTF-8 "). ReplaceAll ("//+ ","%20 ")); ReplaceAll ("//+", "%20") the file name used to process spaces
catch (FileNotFoundException e) {
Downloadfilemessage= "The file does not exist on the server";
return INPUT;
catch (Unsupportedencodingexception e) {
Downloadfilemessage= "Other errors";
return INPUT;
}
return SUCCESS;
}
5. Error handling of Download
<script language= "javascript" >
var Downloadfilemessage = "<%=request.getattribute (" Downloadfilemessage ")%>";
if (downloadfilemessage!= "null") {
alert (downloadfilemessage);
}
</script>