The implementation code of the struts2 file download function is as follows:
Action File
public class DownloadLoadAction extends ActionSupport { /** * */ private static final long serialVersionUID = 5879762231742395104L; private String fileName;//The file name requested by the user private String inputPath;//The path to download the resource (set in the struts configuration file) public void setInputPath(String inputPath) { 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); //Prevent users from requesting unsafe resources if(!downloadFile.startsWith(downloadDir)) { return null; } return "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 default file name of the file 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> </li>
struts.xml:
<action name="download_*_*" method="{2}"> <param name="inputPath">/upload</param> <!-- result type set to stream --> <result name="download_success" type="stream"> <!-- MIME type--> <param name="contentType">application/octet-stream</param> <!-- The value of inputName corresponds to the method name of the action to obtain the input stream resource (the getInputStream method is defined in the action, and the return type is InputStream) --> <param name="inputName">inputStream</param> <!-- Set the file with attachments to dynamically get the file name (define the getDownloadFileName method in action) --> <param name="contentDisposition">attachment;filename="${downloadFileName}"</param> <!-- Set the buffer size--> <param name="bufferSize">2048</param> </result> </action>The above is the relevant content of Struts2 implementation of file download function code sharing (file name transcoding in Chinese) introduced to you by the editor. I hope it will be helpful to everyone!