java后臺(tái)批量下載文件并壓縮成zip下載的方法
本文實(shí)例為大家分享了java后臺(tái)批量下載文件并壓縮成zip下載的具體代碼,供大家參考,具體內(nèi)容如下
因項(xiàng)目需要,將服務(wù)器上的圖片文件壓縮打包zip,下載到本地桌面。
首先,前端js:
function doQueryPic() {
var picsDate = $("#picsDate").val();
var piceDate = $("#piceDate").val();
var picInst = $("#pic_inst").combotree("getValue");
var svrCode = $("#pic_svr_code").val();
var picsTime = $("#pic_stime").val();
var piceTime = $("#pic_etime").val();
if (svrCode == null) {
$.messager.alert('提示', "請(qǐng)輸入交易查詢(xún)代號(hào)");
return;
}else{
$.ajax({
type: "POST",
url: 'queryPic.translog.action',
data: {f_brno:picInst,f_sdate:picsDate,f_edate:piceDate,f_svr_code:svrCode,f_stime:picsTime,f_etime:piceTime},
success: function(rcdata){
if(rcdata.success){
var rows = rcdata.picInfo;
var detailHtml = "<table class='my-form-table' cellpadding='0' cellspacing='0' width='90%' align='center'><thead><tr><th style='width: 5%;text-align: center'><input type='checkbox' onclick='swapCheck()' />全選</th><th style='width: 10%;text-align: center'>日期</th><th style='width: 10%;text-align: center'>有無(wú)影像</th><th style='width: 23%;text-align: center'>交易名稱(chēng)</th><th style='width: 10%;text-align: center'>交易狀態(tài)</th><th style='width: 12%;text-align: center'>設(shè)備編號(hào)</th><th style='width: 10%;text-align: center'>交易代號(hào)</th><th style='width: 10%;text-align: center'>所屬機(jī)構(gòu)</th><th style='width: 10%;text-align: center'>交易時(shí)間</th></tr></thead><tbody>";
for(var i = 0;i < rows.length;i++){
detailHtml = detailHtml + "<tr><td align='center'><input type='checkbox' name='pictureID' value='"+ rows[i].F_DATE + rows[i].F_ICS_BATCH +"' /></td><td>" + rows[i].F_DATE + "</td><td>" + rows[i].ISHASIMG + "</td><td>" + rows[i].F_TX_NAME + "</td><td>" + rows[i].F_STUS + "</td><td>" + rows[i].F_DEV_ID + "</td><td>" + rows[i].F_SVR_CODE + "</td><td>" + rows[i].F_BRNO + "</td><td>" + rows[i].F_TIME + "</td></tr>";
}
detailHtml = detailHtml + "</tbody></table>";
document.getElementById("details").innerHTML = detailHtml;
}else{
$.messager.alert('提示',rcdata.errmsg);
}
},
error:function(){
alert("查詢(xún)失敗!");
}
});
}
}
以上代碼是查詢(xún)到相關(guān)數(shù)據(jù)后,顯示在界面上,然后按客戶(hù)需要可以自己選擇下載哪幾條數(shù)據(jù)保存。
附上CheckBox全選/取消全選js代碼
//checkbox 全選/取消全選
var isCheckAll = false;
function swapCheck() {
if (isCheckAll) {
$("input[type='checkbox']").each(function() {
this.checked = false;
});
isCheckAll = false;
} else {
$("input[type='checkbox']").each(function() {
this.checked = true;
});
isCheckAll = true;
}
}
下面代碼是用來(lái)后臺(tái)交互的,提示一下,下載文件都不要用ajax來(lái)送數(shù)據(jù),我之前就是ajax做的,一直沒(méi)法下載,困擾了一整天后來(lái)才發(fā)現(xiàn)的,注釋部分就是ajax代碼,大家作為參考可以看一下:
function downLoadPic() {
var arr = new Array();
var picIDs = document.getElementsByName("pictureID");
for (i = 0; i < picIDs.length; i++) {
if (picIDs[i].checked) {
arr.push(picIDs[i].value);
}
}
if (arr.length <= 0 ) {
$.messager.alert('提示', "無(wú)下載內(nèi)容!");
return;
}else{
$('#formPic').attr('action','downLoadPic.translog.action');
$("#formPic").form('submit',{
onSubmit:function(){
},
success:function(data){
$.messager.alert('提示','圖片下載成功','info');
}
});
/**
*$.ajax({
type: "POST",
url: 'downLoadPic.translog.action',
data: {pictureList:JSON.stringify(arr)},
success: function(rcdata){
if(rcdata.success){
$.messager.show({
title : '成功',
msg : rcdata.errmsg
});
}else{
$.messager.alert('提示',rcdata.errmsg);
}
},
error:function(){
alert("查詢(xún)失敗!");
}
}); */
}
}
接下來(lái)是后臺(tái)交互,首先是controller控制層:
/**
* 圖片批量下載
* @param request
* @param response
* @return
* @throws IOException
*/
public void downLoadPic(HttpServletRequest request,HttpServletResponse response) throws IOException{
//Map<String, Object> params = getParameters(request);
String[] pictureIDs = request.getParameterValues("pictureID");
Authentication au=getAuthentication(request);
service.downLoadPic(pictureIDs, au, request, response);
return ;
}
service層:
public void downLoadPic(String[] params,Authentication au,HttpServletRequest request,HttpServletResponse response) throws IOException {
//壓縮文件初始設(shè)置
String path=System.getProperty("ics.webapp.root");//這個(gè)是服務(wù)器路徑地址,request.getSession().getServletContext().getRealPath() 也一樣能
String fileZip = au.getUsername()+"-"+au.getAttribute("F_BRNO")+ "Pictures.zip";
String filePath = path+"\\" + fileZip;//之后用來(lái)生成zip文件
//filePathArr為根據(jù)前臺(tái)傳過(guò)來(lái)的信息,通過(guò)數(shù)據(jù)庫(kù)查詢(xún)所得出的pdf文件路徑集合(具體到后綴)
List<Map<String, Object>> fileNameArr = new ArrayList<Map<String,Object>>();
//JSONArray jsons = JSONArray.fromObject(params.get("pictureList"));
/**
*List<String> pictureIDs = new ArrayList<String>();
for(Object obj:jsons){
pictureIDs.add(obj.toString());
}
*/
for (int i = 0; i < params.length; i++) {
Map<String, Object> speMap = new HashMap<String, Object>();
speMap.put("f_date", params[i].substring(0, 8));
speMap.put("f_ics_batch", params[i].substring(8));
List<Map<String, Object>> reclists=dao.queryLogInfo(speMap);
for (int j = 0; j < reclists.size(); j++) {
fileNameArr.add(reclists.get(j));
}
}
//需要壓縮的文件--包括文件地址和文件名
//String[] pathtytytyt ={"D:\\13.jpg","D:\\1212.jpg"};
// 要生成的壓縮文件地址和文件名稱(chēng)
//String desPath = "D:\\DOWNLOADS\\new.zip";
File zipFile = new File(filePath);
ZipOutputStream zipStream = null;
FileInputStream zipSource = null;
BufferedInputStream bufferStream = null;
try {
//構(gòu)造最終壓縮包的輸出流
zipStream = new ZipOutputStream(new FileOutputStream(zipFile));
for(int i =0;i<fileNameArr.size();i++){
File file = new File((String) fileNameArr.get(i).get("F_FILENAME"));
//File file = new File(pathtytytyt[i]);
//將需要壓縮的文件格式化為輸入流
zipSource = new FileInputStream(file);
//壓縮條目不是具體獨(dú)立的文件,而是壓縮包文件列表中的列表項(xiàng),稱(chēng)為條目,就像索引一樣
//這里的name就是文件名,文件名和之前的重復(fù)就會(huì)導(dǎo)致文件被覆蓋,在這用i加文件名進(jìn)行單一文件識(shí)別
ZipEntry zipEntry = new ZipEntry(i+file.getName());
//定位該壓縮條目位置,開(kāi)始寫(xiě)入文件到壓縮包中
zipStream.putNextEntry(zipEntry);
//輸入緩沖流
bufferStream = new BufferedInputStream(zipSource, 1024 * 10);
int read = 0;
//創(chuàng)建讀寫(xiě)緩沖區(qū)
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 {
//關(guān)閉流
try {
if(null != bufferStream) bufferStream.close();
if(null != zipStream) zipStream.close();
if(null != zipSource) zipSource.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 寫(xiě)流文件到前端瀏覽器
ServletOutputStream os = response.getOutputStream();
response.setContentType("application/x-octet-stream");
response.setContentLength((int) zipFile.length());
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileZip, "UTF-8"));
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(filePath));
bos = new BufferedOutputStream(os);
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
os.flush();
os.close();
} catch (IOException e) {
throw e;
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
File obj = new File(filePath);
if (obj.exists()) {
obj.delete();//刪除服務(wù)器本地產(chǎn)生的臨時(shí)壓縮文件
}
}*/
//進(jìn)行瀏覽器下載
//獲得瀏覽器代理信息
final String userAgent = request.getHeader("USER-AGENT");
//判斷瀏覽器代理并分別設(shè)置響應(yīng)給瀏覽器的編碼格式
String finalFileName = null;
if(StringUtils.contains(userAgent, "MSIE")||StringUtils.contains(userAgent,"Trident")){//IE瀏覽器
finalFileName = URLEncoder.encode(fileZip,"UTF-8");
System.out.println("IE瀏覽器");
}else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐瀏覽器
finalFileName = URLEncoder.encode(fileZip,"UTF-8");
}else{
finalFileName = URLEncoder.encode(fileZip,"UTF-8");//其他瀏覽器
}
response.setContentType("application/x-octet-stream");//告知瀏覽器下載文件,而不是直接打開(kāi),瀏覽器默認(rèn)為打開(kāi)
response.setHeader("Content-Disposition" ,"attachment;filename=" +finalFileName);//下載文件的名稱(chēng)
ServletOutputStream servletOutputStream=response.getOutputStream();
DataOutputStream temps = new DataOutputStream(servletOutputStream);
DataInputStream in = new DataInputStream(new FileInputStream(filePath));//瀏覽器下載文件的路徑
byte[] b = new byte[2048];
File reportZip=new File(filePath);//之后用來(lái)刪除臨時(shí)壓縮文件
try {
while ((in.read(b)) != -1) {
temps.write(b);
}
temps.flush();
} catch (Exception e) {
e.printStackTrace();
optLogsvc.saveLog(au.getUsername(), au.getAttribute("F_BRNO"), au.getAttribute("F_LSTIP"),
TOptlogService.TYPE_MR, "", au.getUsername() + "批量下載圖片"+fileZip+"失??!");
}finally{
if(temps!=null) temps.close();
if(in!=null) in.close();
if(reportZip!=null) reportZip.delete();//刪除服務(wù)器本地產(chǎn)生的臨時(shí)壓縮文件
servletOutputStream.close();
}
/**
*if (picInfolList.size() > 0) {
rc.put("success", true);
rc.put("picInfo", picInfolList);
optLogsvc.saveLog(au.getUsername(), au.getAttribute("F_BRNO"), au.getAttribute("F_LSTIP"),
TOptlogService.TYPE_MR, "", au.getUsername() + "查詢(xún)批量下載"+params.get("f_svr_code")+"成功!");
} else {
rc.put("success", false);
rc.put("errmsg", "test info");
optLogsvc.saveLog(au.getUsername(), au.getAttribute("F_BRNO"), au.getAttribute("F_LSTIP"),
TOptlogService.TYPE_MR, "", au.getUsername() + "查詢(xún)批量下載"+params.get("f_svr_code")+"失?。?);
}*/
optLogsvc.saveLog(au.getUsername(), au.getAttribute("F_BRNO"), au.getAttribute("F_LSTIP"),
TOptlogService.TYPE_MR, "", au.getUsername() + "批量下載圖片"+fileZip+"成功!");
return ;
}
里面夾雜了json數(shù)組轉(zhuǎn)格式問(wèn)題,前端json傳過(guò)來(lái)的如果是json.stringify格式化的,到后臺(tái)就得用這種方式進(jìn)行解析。
本人排版能力不咋樣,大家將就看看,那邊判斷瀏覽器的也是網(wǎng)上抄的,結(jié)果發(fā)現(xiàn)根本沒(méi)有用,無(wú)法識(shí)別中文,最后妥協(xié)了還是使用英文做文件名。如果有碰到中文亂碼的,大家可以百度再搜搜,有其他人寫(xiě)過(guò)類(lèi)似文章,我沒(méi)精力研究了。
這個(gè)是壓縮服務(wù)器上本身存在的文件方法,之前百度相關(guān)文章還看到過(guò)獲取網(wǎng)絡(luò)圖片并壓縮下載的,有點(diǎn)意思。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
java中File類(lèi)應(yīng)用遍歷文件夾下所有文件
這篇文章主要為大家詳細(xì)介紹了java中File類(lèi)應(yīng)用遍歷文件夾下所有文件,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-08-08
java 中 poi解析Excel文件版本問(wèn)題解決辦法
這篇文章主要介紹了java 中 poi解析Excel文件版本問(wèn)題解決辦法的相關(guān)資料,需要的朋友可以參考下2017-08-08
Java Servlet線程中AsyncContext異步處理Http請(qǐng)求
這篇文章主要介紹了Java Servlet線程中AsyncContext異步處理Http請(qǐng)求及在業(yè)務(wù)中應(yīng)用,AsyncContext是Servlet 3.0使Servlet 線程不再需要一直阻塞,直到業(yè)務(wù)處理完畢才能再輸出響應(yīng),最后才結(jié)束該Servlet線程2023-03-03
淺談SpringBoot 中關(guān)于自定義異常處理的套路
這篇文章主要介紹了淺談SpringBoot 中關(guān)于自定義異常處理的套路,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04
全面了解JAVA_BaseDAO數(shù)據(jù)處理類(lèi)
下面小編就為大家?guī)?lái)一篇全面了解JAVA_BaseDAO數(shù)據(jù)處理類(lèi)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-07-07
RestTemplate的DELETE及PUT等請(qǐng)求方法使用精講
這篇文章主要為大家介紹了RestTemplate的DELETE及PUT等請(qǐng)求方法的使用精講,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2022-03-03

