【发布时间】:2016-06-22 12:04:23
【问题描述】:
我在我的 xpage 中使用此代码从远程服务器下载文件。当用户从 xpage 中单击下载按钮时,会打开一个新的 download.xsp 页面并运行以下代码。
#{javascript:
var exCon = facesContext.getExternalContext();
var response = exCon.getResponse();
var out = response.getOutputStream();
var zipfile = sessionScope.thezip;
var dname = zipfile.substring(zipfile.lastIndexOf("\\")+1);
dl.download(zipfile,dname);
sessionScope.thezip = null;
response.setContentType("application/zip, application/octet-stream");
response.addHeader("Content-disposition","attachment; filename="+dname);
response.setHeader("Cache-Control", "no-cache");
facesContext.responseComplete();
out.close();
Download 方法 (db.download(string,string)) 是一种 Java 方法,它作为托管 bean 被带到 xpage。
public void download(String filepath, String dname){
Connection con = null;
PreparedStatement stm = null;
ResultSet rs = null;
try{
Class.forName(jdbcClass);
con = DriverManager.getConnection(url);
String insSql = "INSERT INTO Cache(name,zip) SELECT '"+filepath+"',* FROM OPENROWSET(BULK N'"+filepath+"', SINGLE_BLOB) AS import;";
stm = con.prepareStatement(insSql);
stm.executeUpdate();
String sql = "SELECT TOP 1 * FROM Cache where name = ?;";
stm = con.prepareStatement(sql);
stm.setString(1, filepath);
rs = stm.executeQuery();
while(rs.next()){
InputStream zip = rs.getBinaryStream("zip");
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
response.setContentType("application/zip, application/octet-stream");
response.setHeader("Content-disposition","attachment; filename="+dname);
response.setHeader("Cache-Control", "no-cache");
byte[] buf = new byte[8192];
int c = 0;
while ((c = zip.read(buf, 0, buf.length)) > 0) {
OutputStream o = response.getOutputStream();
o.write(buf, 0, c);
o.close();
}
zip.close();
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stm!=null){stm.close();}
if(rs!=null){rs.close();}
if(con!=null){con.close();}
}catch(Exception ex){ex.printStackTrace();}
}
}
此 java 代码运行 sql 查询以获取 zip 文件作为字节并将其存储在表中。然后它选择这一行并将字节返回给调用者 java 方法。这样我就得到了远程文件,因为没有网络服务器来提供 url。
我的问题是如何使用 httpResponse outputStream 来下载 2 或 3 个文件?如果我复制粘贴代码,我只会得到第一个文件。我尝试不关闭 outputStream 我收到流已在使用中的错误。
有人知道吗?
P.S:如果我只想下载 1 个文件,上面的代码已经过测试并且可以正常工作。
【问题讨论】:
标签: java servlets xpages lotus-domino outputstream