本文實(shí)例為大家分享了java后臺(tái)批量下載文件并壓縮成zip下載的具體代碼,供大家參考,具體內(nèi)容如下
因項(xiàng)目需要,將服務(wù)器上的圖片文件壓縮打包zip,下載到本地桌面。
首先,前端js:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
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)輸入交易查詢代號(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'>交易名稱</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( "查詢失敗!" ); } }); } } |
以上代碼是查詢到相關(guān)數(shù)據(jù)后,顯示在界面上,然后按客戶需要可以自己選擇下載哪幾條數(shù)據(jù)保存。
附上checkbox全選/取消全選js代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
//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代碼,大家作為參考可以看一下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
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("查詢失敗!"); } }); */ } } |
接下來(lái)是后臺(tái)交互,首先是controller控制層:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
/** * 圖片批量下載 * @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層:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
|
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ù)查詢所得出的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"}; // 要生成的壓縮文件地址和文件名稱 //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),稱為條目,就像索引一樣 //這里的name就是文件名,文件名和之前的重復(fù)就會(huì)導(dǎo)致文件被覆蓋,在這用i加文件名進(jìn)行單一文件識(shí)別 zipentry zipentry = new zipentry(i+file.getname()); //定位該壓縮條目位置,開始寫入文件到壓縮包中 zipstream.putnextentry(zipentry); //輸入緩沖流 bufferstream = new bufferedinputstream(zipsource, 1024 * 10 ); int read = 0 ; //創(chuàng)建讀寫緩沖區(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(); } } /** * 寫流文件到前端瀏覽器 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" ); //告知瀏覽器下載文件,而不是直接打開,瀏覽器默認(rèn)為打開 response.setheader( "content-disposition" , "attachment;filename=" +finalfilename); //下載文件的名稱 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() + "查詢批量下載"+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() + "查詢批量下載"+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é)了還是使用英文做文件名。如果有碰到中文亂碼的,大家可以百度再搜搜,有其他人寫過(guò)類似文章,我沒(méi)精力研究了。
這個(gè)是壓縮服務(wù)器上本身存在的文件方法,之前百度相關(guān)文章還看到過(guò)獲取網(wǎng)絡(luò)圖片并壓縮下載的,有點(diǎn)意思。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/blackalone/article/details/81033749