這是我自己寫的一個批量下載,是寫在Action中的,首先是將要下載的檔案打包成.zip的檔案,在下載。這裡供大家參考,望大家找出更好的方法。註:這是從伺服器上下載
response.setContentType("text/html;charset=GBK"); //中文亂碼處理
String str=request.getParameter("str"); //擷取需要下載檔案的ID字串
String[] num=str.split(",");
List listall=(List)request.getSession().getAttribute("listupload");
//儲存下載的檔案路徑
File[] files=new File[num.length];
for(int i=0;i<listall.size();i++){
UploadInfo upinfo=(UploadInfo)listall.get(i);
for(int k=0;k<num.length;k++){
if(upinfo.getUpId().equals(new Integer(num[k]))){
String upname=upinfo.getUpName();
String path=servlet.getServletContext().getRealPath("/")+"uploads//"+upname;
files[k]=new File(path);
}
}
}
byte[] bt=new byte[8192];
//產生zip檔案的名稱,必須寫明儲存路徑,這裡是儲存到伺服器上,這樣你下載下來的才會到你自己的電腦上。如果你是在你自己電腦上下載 那就不需要儲存在伺服器了。
String strzipName=servlet.getServletContext().getRealPath("/")+"uploads//"+"resume.zip";
String strs="resume.zip";
try {
ZipOutputStream zout=new ZipOutputStream(new FileOutputStream(strzipName));
//迴圈下載每個檔案並讀取內容
for(int j=0;j<files.length;j++){
FileInputStream is=new FileInputStream(files[j]);
ZipEntry ze=new ZipEntry(URLEncoder.encode(files[j].getName(), "UTF-8"));//設定檔案編碼格式
zout.putNextEntry(ze);
int len;
//讀取下載檔案內容
while((len=is.read(bt))>0){
zout.write(bt, 0, len);
}
zout.closeEntry();
is.close();
}
zout.close();
this.toUpload(response, strs);//調用下載方法
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//下載公用方法
public void toUpload(HttpServletResponse response,String str){
try {
String path=servlet.getServletContext().getRealPath("/")+"uploads//"+str;
if(!"".equals(path)){
File file=new File(path);
if(file.exists()){
InputStream ins=new FileInputStream(path);
BufferedInputStream bins=new BufferedInputStream(ins);//放到緩衝流裡面
OutputStream outs=response.getOutputStream();//擷取檔案輸出IO流
BufferedOutputStream bouts=new BufferedOutputStream(outs);
response.setContentType("application/x-download");//設定response內容的類型
response.setHeader("Content-disposition","attachment;filename="+ URLEncoder.encode(str, "UTF-8"));//設定頭部資訊
int bytesRead = 0;
byte[] buffer = new byte[8192];
//開始向網路傳輸檔案流
while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
bouts.write(buffer, 0, bytesRead);
}
bouts.flush();//這裡一定要調用flush()方法
ins.close();
bins.close();
outs.close();
bouts.close();
}
else{
response.sendRedirect("../error.jsp");
}
}
else{
response.sendRedirect("../error.jsp");
注;這裡面不要用到PrintWriter out=response.getWriter();這裡調用了response對象,後面下載調用時就會出錯。這裡要是想都用,希望大家找到解決辦法。
}
} catch (IOException e) {
e.printStackTrace();
}
}