在做下載功能時,遇到要同時下載多個文件的情況。試過多種方法,最好的一種就是把這些需要下載的文件,打包成壓縮文件,然後下載這個壓縮文件。
下面是實現的代碼:
package com.cbkcbp.businessreport.businessreport01;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletResponse;
public class Test {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
ZipOutputStream zipOut = null;
String zipUrl = "";
//response:是要通過提交表單來響應
HttpServletResponse response = null;
String zipName = "test.zip";
String attachment = "attachment";
byte[] buffer = new byte[1024];
//Zip文件產出的路徑
zipUrl = "c:test/test1.xls※c:test/test2.xls※c:test/test3.xls";
zipOut = new ZipOutputStream(new FileOutputStream(zipUrl));
//以"※"為分割符,截取報表Url(因為可能會有多份文件需要壓縮)
String [] attachUrls = zipUrl.split("※");
for(int i=0; i < attachUrls.length; i++){
//截取文件名,比如:"c:test/test.xls" 可截取得:"test.xls"
File tempFile =new File(attachUrls[i].trim());
//文件名
String fileName = tempFile.getName();
FileInputStream fis = new FileInputStream(attachUrls[i].trim());
zipOut.putNextEntry(new ZipEntry(fileName));
int len;
//讀入需要下載文件的內容,打包到zip文件
while((len = fis.read(buffer))>0) {
zipOut.write(buffer,0,len);
}
zipOut.closeEntry();
fis.close();
}
//讀取產出壓縮文件的字節流byte
byte [] reportByte = Test.toByteArray(zipUrl);
//將打包好的壓縮文件輸出Client端
Test.processWebOutput(reportByte, zipName, response, attachment);
}
/**
* 根據文件的路徑讀取文件的字節流byte
* @param fileName
* @return
* */
public static byte[] toByteArray(String fileName) throws IOException{
File file = new File(fileName);
if(!file.exists()){
throw new FileNotFoundException(fileName);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream((int)file.length());
BufferedInputStream bis = null;
try{
bis = new BufferedInputStream(new FileInputStream(file));
int buf_size = 1024;
byte[] buffer = new byte[buf_size];
int len = 0;
while(-1 != (len = bis.read(buffer,0,buf_size))){
bos.write(buffer,0,len);
}
return bos.toByteArray();
}catch (IOException e) {
e.printStackTrace();
throw e;
}finally{
try{
bis.close();
}catch (IOException e) {
e.printStackTrace();
}
bos.close();
}
}
/**
* 將打包好的壓縮文件輸出在Client端
* @param bytes
* @param fileName
* @param response
* @param attachment
* @throws Exception
*/
public static void processWebOutput(byte[] bytes, String fileName
, HttpServletResponse response, String attachment){
OutputStream ouputStream = null;
try{
response.reset();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition",attachment +" ; filename=" + fileName);
ouputStream = response.getOutputStream();
ouputStream.write(bytes);
}catch(Exception e){
e.printStackTrace();
}finally{
try{
ouputStream.flush();
ouputStream.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
}
}