mik*_*_x_ 2 java servlets outputstream lotus-domino xpages
我在我的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();
Run Code Online (Sandbox Code Playgroud)
下载方法(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();}
}
}
Run Code Online (Sandbox Code Playgroud)
此java代码运行sql查询以获取zip文件作为字节并将其存储在表中.然后它选择此行并将字节返回给调用者java方法.这样我就可以获得远程文件,因为没有网络服务器来提供网址.
我的问题是如何使用httpResponse outputStream来下载2或3个文件?如果我复制粘贴代码我只得到第一个文件.我尝试不关闭outputStream我得到一个错误,该流已被使用.
有谁有想法吗?
PS:以上代码经过测试,如果我只想下载1个文件,可以正常工作.
您最好的选择可能是使用java.util.zip
类动态地将多个文件合并到另一个ZIP文件中.您可以包装输出流,ZipOutputStream
然后循环遍历ResultSet行,创建ZipEntry
对象以区分其中的每个文件.