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

来源:互联网 发布:淘宝网高级搜索在哪里 编辑:程序博客网 时间:2024/05/29 13:22

续《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" onclick="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