下面一段代碼給大家分享JavaWeb實現壓縮多個文件并下載功能,具體代碼如下所示:
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
|
//文件名稱 String[] names={ "one.jpg" , "two.jpg" , "three.jpg" , "four.jpg" }; //四個文件流 FileInputStream input1 = new FileInputStream( new File( "文件路徑" )); FileInputStream input2 = new FileInputStream( new File( "文件路徑" )); FileInputStream input3 = new FileInputStream( new File( "文件路徑" )); FileInputStream input4 = new FileInputStream( new File( "文件路徑" )); FileInputStream[] inputs={input1,input2,input3,input4}; //ZIP打包圖片 File zipFile = new File( "壓縮文件存放路徑" ); byte [] buf = new byte [ 1024 ]; int len; ZipOutputStream zout= new ZipOutputStream( new FileOutputStream(zipFile)); for ( int i = 0 ; i < inputs.length; i++) { FileInputStream in =inputs[i]; zout.putNextEntry( new ZipEntry(names[i])); while ((len = in.read(buf)) > 0 ) { zout.write(buf, 0 , len); } zout.closeEntry(); in.close(); } zout.close(); //下載圖片 FileInputStream zipInput = new FileInputStream(zipFile); OutputStream out = response.getOutputStream(); response.setContentType( "application/octet-stream" ); response.setHeader( "Content-Disposition" , "attachment; filename=images.zip" ); while ((len=zipInput.read(buf))!= - 1 ){ out.write(buf, 0 ,len); } zipInput.close(); out.flush(); out.close(); //刪除壓縮包 zipFile.delete(); |
總結
以上所述是小編給大家介紹的JavaWeb實現壓縮多個文件并下載實例詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://www.cnblogs.com/yzjSince92/p/6282869.html