自己用到的SpringMVC多檔案下載
js介面
function editCustomer(ipid) {
$.getJSON("1111/2222.html", {//上傳路徑
ipid : ipid
}, function(data) {
alert(data)
});
}
頁面資訊
<a href="javascript:void(0)" onclick="editCustomer(2)">檔案下載</a>
後臺操作
List<String> filePaths = new ArrayList<String>();
List<Object[]> fileList = f12022ServiceImpl.getFileInfo(params);//獲取檔案路徑
//迴圈得出路徑加到集合裡
if (fileList != null && fileList.size() > 0) {
fileName = (String) fileList.get(0)[3];
filePath = (String) fileList.get(0)[5];
fileServerName = (String) fileList.get(0)[4];
System.out.println(filePath+fileServerName);
filePaths.add(filePath+fileServerName);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
//下載到那個位置
String desPath = "C:\\Users\\Administrator\\Desktop\\DownLoad.zip";
File zipFile = new File(desPath);
ZipOutputStream zipStream = null;
FileInputStream zipSource = null;
BufferedInputStream bufferStream = null;
try {
//構造最終壓縮包的輸出流
zipStream = new ZipOutputStream(new FileOutputStream(zipFile));
for (String string : filePaths) {
File file = new File(string);
//將需要壓縮的檔案格式化為輸入流
zipSource = new FileInputStream(file);
//壓縮條目不是具體獨立的檔案,而是壓縮包檔案列表中的列表項,稱為條目,就像索引一樣
ZipEntry zipEntry = new ZipEntry(file.getName());
//定位該壓縮條目位置,開始寫入檔案到壓縮包中
zipStream.putNextEntry(zipEntry);
//輸入緩衝流
bufferStream = new BufferedInputStream(zipSource, 1024 * 10);
int read = 0;
//建立讀寫緩衝區
byte[] buf = new byte[1024 * 10];
while((read = bufferStream.read(buf, 0, 1024 * 10)) != -1)
{
zipStream.write(buf, 0, read);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//關閉流
try {
if(null != bufferStream) bufferStream.close();
if(null != zipStream) zipStream.close();
if(null != zipSource) zipSource.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}