struts文件下载

一: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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值