<body> <a href="DownloadAction?fileName=荷花.txt">下載文檔</a> <br /> <a href="DownloadAction?fileName=荷花.jpg">下載圖片</a> <br /> </body>
fileName帶文件名後綴。瀏覽器
public class DownloadAction extends ActionSupport { private String fileName; public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public InputStream getInputStream(){ return ServletActionContext.getServletContext().getResourceAsStream("resource/" + fileName); } @Override public String execute() throws Exception { return SUCCESS; } }
<action name="DownloadAction" class="action.DownloadAction"> <result name="success" type="stream"> <!-- 指定action中獲取輸入流的方法,getInputStream,約定:去掉get,後面部分轉化爲camel寫法 --> <param name="inputName">inputStream</param> <!-- 設置瀏覽器對此stream(輸入流)的處理方式:保存爲文件,filename指定文件名 --> <param name="contentDisposition">attachment;filename=${fileName}</param> <!-- 設置緩衝大小,默認單位字節 --> <param name="bufferSize">4096</param> <!-- 解決中文文件名出錯 --> <param name="encode">true</param> </result> </action>