欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JSP 多个文件打包下载代码

程序员文章站 2023-12-02 20:14:58
现把该程序主要代码贴下,供大家需要的时候参考下: <%@page import="java.util.*, java.net.*, java.text.*, java...
现把该程序主要代码贴下,供大家需要的时候参考下:
<%@page import="java.util.*,
java.net.*,
java.text.*,
java.util.zip.*,
java.io.*" %>
<%!
static vector expandfilelist(string[] files, boolean incldirs){
vector v = new vector();
if (files == null) return v;
for (int j=0; j < files.length; i++) v.add (new file(urldecoder.decode(files[j])));
for (int i=0; i < v.size(); i++){
file f = (file) v.get(i);
if (f.isdirectory()){
file[] fs = f.listfiles();
for (int n = 0; n < fs.length; n++) v.add(fs[n]);
if (!incldirs){
v.remove(i);
i--;
}
}
}
return v;
}
class writer2stream extends outputstream{
writer out;
writer2stream (writer w){
super();
out = w;
}
public void write(int i) throws ioexception{
out.write(i);
}
public void write(byte[] b) throws ioexception{
for (int j=0;j<b.length;j++){
int n=b[j];
//convert byte to ubyte
n=((n>>>4)&0xf)*16+(n&0xf);
out.write (n);
}
}
public void write(byte[] b, int off, int len) throws ioexception{
for (int j = off; j < off + len; j++){
int n=b[j];
n = ((n>>>4)&0xf)*16+(n&0xf);
out.write(n);
}
}
} 
%>
<%
/////下载压缩文件包
vector v = expandfilelist(request.getparametervalues("selfile"), false);
if (v.size() == 0){
request.setattribute("error", "no files selected");
}
else{
file dir_file = new file(request.getrealpath("") + "/myfile/");
int dir_l = dir_file.getabsolutepath().length();
response.setcontenttype ("application/zip");
response.setheader ("content-disposition", "attachment;filename=\"downloadname.rar\"");
out.clearbuffer();
zipoutputstream zipout = new zipoutputstream(new writer2stream(out));
zipout.setcomment("download selected files \nas one winrar file:\ndownloadname.rar");
zipout.setlevel(1);
for (int i=0;i<v.size();i++){
file f = (file)v.get(i);
if (f.canread()){
zipout.putnextentry(new zipentry(f.getabsolutepath().substring(dir_l+1)));
bufferedinputstream fr = new bufferedinputstream(new fileinputstream(f));
byte buffer[] = new byte[0xffff];
int b;
while ((b=fr.read())!=-1) zipout.write(b);
fr.close();
zipout.closeentry();
}
}
zipout.finish();
out.flush();
}
%>