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"去掉即可

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

被折叠的 条评论
为什么被折叠?



