jspsmart实现页面不跳转上传和下载文件(二)

续《jspsmart实现页面不跳转上传和下载文件(一)》,这里继续讲解一下页面不跳转实现文件的下载。

要实现页面不跳转,这里还需要iframe,在主界面上添加如下:

<iframe src="" name="attach" style="display:none"></iframe><form method="post" id="attachForm" action="<%=path%>/service/communication/bulletinIssueDownload.jsp?filepath=<%=filePath%>&filename=<%=fileName%>" enctype="multipart/form-data" method="POST" target="attach"><a href="#" id="attach" target="attach" οnclick="downloadAttach();"><%=fileName%></a></form>

其中,downloadAttach()方法如下:

function downloadAttach(){
	var form = document.getElementById("attachForm");
	form.submit();
}

这样在downloadAttach方法中完成了form的提交,由于form的属性:target="attach",其中attach是iframe,所以这样form的提交后页面跳转到iframe中,主页面就不会跳转了。

接下来看看下载逻辑的界面bulletinIssueDownload.jsp:

<%@page import="org.apache.http.protocol.HttpContext"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="com.jspsmart.upload.*"%>
<%
SmartUpload su = new SmartUpload();
try {
    String filepath = new String(request.getParameter("filepath").getBytes( "iso-8859-1" ), "UTF-8" );
    String fileName = new String(request.getParameter("filename").getBytes( "iso-8859-1" ), "UTF-8" );
    su.initialize(getServletConfig(), request, response);
//禁止浏览器自动打开文件,若不设定,浏览器自动寻找相关应用程序打开该附件。
    su.setContentDisposition(null);
    su.downloadFile(filepath,"application/octet-stream",new String(fileName.getBytes("UTF-8"),"iso-8859-1"));
    response.getOutputStream().close();
} catch (Exception e){
	%>
	<SCRIPT language=javascript>
	alert("附件下载失败,原因:<%=e.getMessage() %>");
	history.back();
	</script>
	<%
}
%>


值得注意的是:

    1、filepath和fileName是两个参数,从request中获取的,如果是中文的话下载就会出错,因为jsp之间传输采用的是iso-8859-1编码格式,所以需要将参数从iso-8859-1转化为utf-8;

     2、下载时后台出现错误:getOutputStream() has already been called for this response,但是这个问题不影响下载。如果看着不爽,请参阅:http://blog.csdn.net/shangyu79/article/details/2591119


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值