Struts的檔案下載功能
阿新 • • 發佈:2018-11-02
Action層:
public String myDownloadFile() { HttpServletResponse response = ServletActionContext.getResponse(); String myFileName = getFilename(); //設定檔名 一般帶有副檔名。是下載後文件的名稱。 try { byte[] buffer = XXXService.readFile(attId); // byte[] 通過id獲取檔案的byte陣列 // 清空response response.reset(); // 設定response的Header response.addHeader("Content-Disposition", "attachment;filename=" + new String(myFileName.getBytes("gb2312"), "ISO8859-1")); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); toClient.write(buffer); toClient.flush(); toClient.close(); } catch (IOException ex) { ex.printStackTrace(); } return null; }
Struts配置檔案:
<action name="myDownloadFile" class="xyz.jangle.base.action.AttachmentAction" method="myDownloadFile">
<result name="success"></result>
</action>
前端html:
<a href="/myDownloadFile.action?attId=fileId">檔名稱.doc</a>