Struts2中文件下载
在struts.xml中配置如下
1 <action name="download" class="cn.itcast.domain.User" method="download"> 2 <result type="stream" name="success"> 3 <param name="contentType">application/octet-stream</param> 4 <param name="inputStream">inputStream</param><!-- 输入是对应的动作类中的那个字段 --> 5 <param name="contentDisposition">attachment;filename=${filename}</param><!-- 要下载的文件名 --> 6 </result>
jsp页面中
user为action中传来的
1 <c:url value="/user/download" var="url"> 2 <c:param name="path" value="${user.path}"></c:param> 3 <c:param name="filename" value="${user.filename}"></c:param> 4 </c:url> 5 <a href="${url}">下载</a>
在User.java中
class User{ private String path; //文件保存的路径 private String filename; //文件名 //文件下载 固定名字 private InputStream inputStream; public InputStream getInputStream() { return inputStream; } public void setInputStream(InputStream inputStream) { this.inputStream = inputStream; } public String download() { String storePath=ServletActionContext.getServletContext().getRealPath("/files"); System.out.println("before" +path +" "+ filename); //事实证明struts2中处理了相关参数, 并且通过url传输传给 path, filename中的值 // path=ServletActionContext.getRequest().getParameter("path"); // filename=ServletActionContext.getRequest().getParameter("filename"); System.out.println("after" +path +" "+ filename); try { inputStream=new FileInputStream(storePath+"\\"+path+"\\"+filename); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return this.SUCCESS; } }