一:xml设置
<action name="down_*" class="gz.itcast.h_upload_down.DownloadAction" method="{1}">
<param name="serverPath">e:/images/</param>
<result name="list">/listFile.jsp</result>
<!-- 下载的返回类型Stream -->
<result name="down" type="stream">
<!-- 往StreamResult 类中的属性注入内容 -->
<!-- 返回给浏览器的文件类型。返回通用的二进制 -->
<param name="contentType">application/octet-stream</param>
<!-- 返回给浏览器的输入流 -->
<param name="inputName">inputStream</param>
<!-- 告诉浏览器的方式下载资源 -->
<!-- ${name}是为了获取action中的getname()方法的数据 -->
<param name="contentDisposition">attachment;filename="${name}"</param>
<!-- 缓存大小-->
<param name="bufferSize">1024</param>
</result>
</action>
二:Action之DownAction
public class DownloadAction extends ActionSupport{
private String serverPath;
private String name;
//列出文件
public String list() throws Exception{
File file=new File(serverPath);
//拿到文件名字列表
String[] list=file.list();
//把文件列表转到jsp页面显示
ActionContext ac=ActionContext.getContext();
Map<String,Object> request=ac.getContextMap();
request.put("list", list);
return "list";
}
//下载文件 必须写输入流
public String down() throws Exception{
return "down";
}
public InputStream getInputStream(){
try {
FileInputStream fis = new FileInputStream(new File(serverPath
+ name));
return fis;
} catch (Exception e) {
// TODO: handle exception
throw new RuntimeException(e);
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getServerPath() {
return serverPath;
}
public void setServerPath(String serverPath) {
this.serverPath = serverPath;
}
三:jsp之listFile.jsp
<body>
<table border="1" width="300px">
<tr>
<th>编号</th>
<th>文件名称</th>
<th>操作</th>
</tr>
<c:forEach items="${list}" var="file" varStatus="varSta">
<tr>
<td>${varSta.count}</td>
<td>${file}</td>
<td><a href="${pageContext.request.contextPath }/upload/down_down?name=${file}">下载</a></td>
</tr>
</c:forEach>
</table>
</body>