您的位置:首页 > 编程语言 > Java开发

struts2文件下载错误提示的解决方法

2011-05-23 14:49 423 查看
1. jsp页面超链接<a href="javascript:void(0)" onclick="downloadFile('${id}')">${name}</a>

2. 表单提交

<form action="downloadFile.html" id="downloadFileForm" method="post" enctype="multipart/form-data" target="downloadFileIframe">
<input type="hidden" id="downloadFileId" name="id"/>
<iframe name="downloadFileIframe" style="display:none"></iframe>
</form>
<script type="text/javascript">
function downloadFile(id){
$("#downloadFileId").val(id);
downloadFileForm.submit();
}
</SCRIPT>

3. struts2.xml

<action name="downloadFile" class="cn.shaviation.frm.webapp.action.FileUploadAction" method="download">
<result name="success" type="stream">
<param name="contentType">${sysfile.type}</param>
<param name="inputName">inputStream</param>
<param name="bufferSize">40960</param>
</result>
<result name="input">/WEB-INF/pages/common/downloadFileErrorMessage.jsp</result>
</action>

4. FileUploadAction中的download方法

public String download() { //下载文件
try {
sysfile = sysfileManager.get(id);
inputStream = new FileInputStream(sysfile.getPath());
getResponse().setHeader("Content-Disposition","attachment; filename="+ URLEncoder.encode(sysfile.getName(), "UTF-8").replaceAll("//+", "%20") ); //replaceAll("//+", "%20")用来处理空格的文件名
} catch (FileNotFoundException e) {
downloadFileMessage="服务器上不存在该文件";
return INPUT;
} catch (UnsupportedEncodingException e) {
downloadFileMessage="其他错误";
return INPUT;
}

return SUCCESS;
}

5. 下载发生错误的处理

<SCRIPT LANGUAGE="javascript">
var downloadFileMessage = "<%=request.getAttribute("downloadFileMessage")%>";
if(downloadFileMessage != "null"){
alert(downloadFileMessage);
}
</SCRIPT>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐