1.在实际应用开发中,文件下载功能也非常常见。
2.最简单的文件下载方式是通过超链接来进行文件下载:
注意:直接通过超链接下载文件,如果浏览器能够读取文件,浏览器会直接读取,而不会下载到本地。并且有安全问题。所以,可以通过action来实现下载。
3.Struts2文件下载功能的实现:
Action实现
public class DownloadAction { private String fileName; public String execute(){ return Action.SUCCESS; } //获取文件流 public InputStream getInputStream() throws FileNotFoundException{ String path=ServletActionContext.getServletContext().getRealPath("/download"); return new FileInputStream(new File(path,fileName)); } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; }}
Struts.xml
inputStream attachment;filename=${fileName}
jsp
或者 Action的另一种写法:
public class DownloadAction { private String fileName; private InputStream inputStream; public String execute() throws FileNotFoundException{ String path=ServletActionContext.getServletContext().getRealPath("/download"); inputStream = new FileInputStream(new File(path,fileName)); return Action.SUCCESS; } public InputStream getInputStream() { return inputStream; } public void setInputStream(InputStream inputStream) { this.inputStream = inputStream; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; }}