目前伺服器多檔案壓縮下載下傳實作
@ApiOperation("導出資料多個")
@RequestMapping(value = "/infoexportfiles", method = {RequestMethod.GET, RequestMethod.POST})
public void infoexportfiles(HttpServletResponse res,@ApiParam(value = "任務id")@RequestParam(value = "ids") String ids) {
try {
List<JSONObject> infoList = getInfoList(ids);
if (infoList.size() > 0) {
List<JSONObject> list = new ArrayList<>();
for (JSONObject info : infoList) {
String path = info.getString("path");
if(StringUtils.isNotEmpty(path)){
String filename = info.getString("filename");
JSONObject jb = new JSONObject();
jb.put("name",filename);
jb.put("path",path);
list.add(jb);
}
}
//建立壓縮檔案需要的空的zip包
String zipName = "resources.zip";
String zipFilePath = taskpath+File.separator+zipName;
//壓縮檔案
File zip = new File(zipFilePath);
if (!zip.exists()){
zip.createNewFile();
}
//建立zip檔案輸出流
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zip));
zipFile(taskpath,zipName, zipFilePath,list,zos);
zos.close();
res.setCharacterEncoding("UTF-8"); //設定編碼字元
res.setContentType("application/octet-stream;charset=UTF-8"); //設定下載下傳内容類型
res.setHeader("Content-disposition", "attachment;filename="+zipName);//設定下載下傳的壓縮檔案名稱
OutputStream out = res.getOutputStream(); //建立頁面傳回方式為輸出流,會自動彈出下載下傳框
//将打包後的檔案寫到用戶端,輸出的方法同上,使用緩沖流輸出
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(zipFilePath));
byte[] buff = new byte[bis.available()];
bis.read(buff);
bis.close();
out.write(buff);//輸出資料檔案
out.flush();//釋放緩存
out.close();//關閉輸出流
}
}catch(Exception e) {
e.printStackTrace();
}
}
/**
* 壓縮檔案
* @param zipBasePath 臨時壓縮檔案基礎路徑
* @param zipName 臨時壓縮檔案名稱
* @param zipFilePath 臨時壓縮檔案完整路徑
* @param list 需要壓縮的檔案路徑集合
* @throws IOException
*/
private String zipFile(String zipBasePath, String zipName, String zipFilePath, List<JSONObject> list,ZipOutputStream zos) throws IOException {
log.info("壓縮檔案");
//循環讀取檔案路徑集合,擷取每一個檔案的路徑
Map<String,String> map = new HashMap<>();
for(JSONObject filePath : list){
File inputFile = new File(filePath.getString("path")); //根據檔案路徑建立檔案
if(inputFile.exists()) { //判斷檔案是否存在
if (inputFile.isFile()) { //判斷是否屬于檔案,還是檔案夾
//建立輸入流讀取檔案
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inputFile));
//将檔案寫入zip内,即将檔案進行打包
String name = filePath.getString("name");
if(map.containsKey(name)){
name = name.substring(0,name.indexOf(".")) +System.currentTimeMillis()+ name.substring(name.indexOf("."));
}
map.put(name,"0");
zos.putNextEntry(new ZipEntry(name));
//寫入檔案的方法,同上
int size = 0;
byte[] buffer = new byte[1024]; //設定讀取資料緩存大小
while ((size = bis.read(buffer)) > 0) {
zos.write(buffer, 0, size);
}
//關閉輸入輸出流
zos.closeEntry();
bis.close();
}
}
}
return null;
}