Struts2完成文件下載功效代碼分享(文件名中文轉碼)。本站提示廣大學習愛好者:(Struts2完成文件下載功效代碼分享(文件名中文轉碼))文章只能為提供參考,不一定能成為您想要的結果。以下是Struts2完成文件下載功效代碼分享(文件名中文轉碼)正文
struts2文件下載功效完成代碼以下所示:
Action文件
public class DownLoadAction extends ActionSupport { /** * */ private static final long serialVersionUID = 5879762231742395104L; private String fileName;//用戶要求的文件名 private String inputPath;//下載資本的途徑(在struts設置裝備擺設文件中設置) 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); //避免用戶要求不平安的資本 if(!downloadFile.startsWith(downloadDir)) { return null; } return "download_success"; } /* * 獲得輸出流資本 */ public InputStream getInputStream() throws Exception { String path = inputPath + File.separatorChar + new String(fileName.getBytes("ISO-8859-1"), "UTF-8"); return ServletActionContext.getServletContext().getResourceAsStream(path); } /* * 獲得下載時文件默許的文件名 */ public String getDownloadFileName() { String downloadFileName = fileName; try { downloadFileName = URLEncoder.encode(downloadFileName, "ISO-8859-1"); } catch (UnsupportedEncodingException e) { e.getMessage(); e.printStackTrace(); } return downloadFileName; } }
jsp文件:
<li> <a href="<%=path%>/download_DownLoadAction_downloadFile.action?fileName=dwr.jar">dwr.jar文件下在</a> </li> <li> <a href="<%=path%>/download_DownLoadAction_downloadFile.action?fileName=Struts2教程.pdf">Struts2教程.pdf文件下在</a> </li>
struts.xml:
<action name="download_*_*" class="com.wang.action.{1}" method="{2}"> <param name="inputPath">/upload</param> <!-- result type設置為stream --> <result name="download_success" type="stream"> <!-- MIME類型 --> <param name="contentType">application/octet-stream</param> <!-- inputName的值與action獲得輸出流資本的辦法名絕對應(action中界說getInputStream辦法,而且前往類型為InputStream) --> <param name="inputName">inputStream</param> <!-- 設置帶附件的文件 靜態獲得文件名(action中界說getDownloadFileName辦法) --> <param name="contentDisposition">attachment;filename="${downloadFileName}"</param> <!-- 設置緩沖年夜小 --> <param name="bufferSize">2048</param> </result> </action>
以上所述是小編給年夜家引見的Struts2完成文件下載功效代碼分享(文件名中文轉碼)的相干內容,願望對年夜家有所贊助!