struts处理上传下载2

本文详细介绍了在使用Struts进行文件下载时遇到的异常问题,并提供了有效的解决方法,包括在下载按钮中使用JavaScript,配置下载表单,以及在Action中正确处理参数和文件流。同时解释了异常产生的原因及解决步骤。

jsp:

下载按钮:

<td><a href="javascript:download('<s:property value='#sample.savepath'/>')"><img src="img/download.png" /> </a></td>

 

在页面再加一个专供下载提交用的form

        <form action="sample/sampleDownload.action" id="sampleDownload" name="sampleDownload" method="post">
         <input type="hidden" name="savepath" id="savepath" />
        </form>

js:

//样本下载
function download(savepath){
 $('#savepath').val(savepath);
 document.getElementById('sampleDownload').submit();
}

 

Action:

 /**
  * 样本文件下载
  *
  * @return
  * @throws UnsupportedEncodingException
  */
 public String sampleDownload() throws UnsupportedEncodingException {
  try {
   String savepath = sRequest.getParameter("savepath");
   String sampleFileName = savepath.substring(savepath.lastIndexOf("/") + 1);
   
   this.inputStream = new FileInputStream(new File(savepath));
   //文件名需要单独转码处理,否则若包含中文则乱码
   this.filename = new String(sampleFileName.getBytes(), "ISO8859-1");
  } catch (FileNotFoundException e) {
   e.printStackTrace();
   request.put(MESSAGE, "文件读取失败!!");
   return ERROR;
  }
  return SUCCESS;
 }

 

 

struts配置文件:

  <!-- 样本下载 -->
  <action name="sampleDownload" class="sampleAction" method="sampleDownload">
    <result name="success" type="stream">
     <param name="contentType">application/octet-stream; charset=UTF-8</param>
     <param name="inputName">inputStream</param>
     <param name="contentDisposition">attachment; filename="${filename}"</param>  
     <param name="bufferSize">2048</param>
    </result>
   </action> 

 

以上配置,struts下载文件时可以正常下载得到文件,但后台会抛出异常:getOutputStream() has already been called for this respon

解决方法:把form里的method="post"去掉即可

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值