本文實例為大家分享了javaweb多文件上傳及zip打包下載的具體代碼,供大家參考,具體內(nèi)容如下
項目中經(jīng)常會使用到文件上傳及下載的功能。本篇文章總結(jié)場景在javaweb環(huán)境下,多文件上傳及批量打包下載功能,包括前臺及后臺部分。
首先明確一點:
無法通過頁面的無刷新ajax請求,直接發(fā)下載、上傳請求。上傳和下載,均需要在整頁請求的基礎(chǔ)上實現(xiàn)。項目中一般通過構(gòu)建form表單形式實現(xiàn)這一功能。
一、多文件上傳
項目需求為實現(xiàn)多圖片上傳功能。參考測試了網(wǎng)上找到的眾多插件方法后,決定選用jquery原始上傳方案。以下按步驟貼出具體代碼。
1、html部分(可省略使用js構(gòu)建)
1
2
3
4
|
<form id= "uploadform" method= "post" enctype= "multipart/form-data" > <input type= "file" hidden name= "fileimage" multiple/> <a href= "javascript:void(0);" rel= "external nofollow" rel= "external nofollow" id= "filesubmit" onclick= "uploadfilemulti()" >上傳資料</a> </form> |
有幾點說明:
1. form中 enctype=”multipart/form-data”
2. 例中使用標(biāo)簽,構(gòu)建submit
2、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
|
var formdata = new formdata($( "#uploadform" )[ 0 ]); formdata.append( "foldname" , "datumlist" ); //設(shè)置父級文件夾名稱 formdata.append( "odercode" , selfordercode); formdata.append( "datumtype" , datumtype); $.ajax({ type: "post" , data: formdata, url: "order/datumlist/batchinsertdatumlists" , contenttype: false , processdata: false , success: function (result) { if (result.success) { //清空框文件內(nèi)容 $( "#fileimage" ).val( "" ); var obj = document.getelementbyid( 'fileimage' ); obj.outerhtml = obj.outerhtml; refreshdatumlist(); showsuccesstoast(result.message); } else { showwarningtoast(result.message); } }, error: function () { showerrortoast( '請求失敗!' ) } }); |
以上有幾點說明:
1. var formdata = new formdata($(“#uploadform”)[0]);
2. 使用 formdata.append(“odercode”, selfordercode); 添加其他參數(shù)
java后臺
1
2
|
multiparthttpservletrequest mrequest = (multiparthttpservletrequest) request; list<multipartfile> files = mrequest.getfiles( "fileimage" ); |
以上有幾點說明:
1. 獲取multiparthttpservletrequest,對應(yīng)file標(biāo)簽的name
二、文件批量下載
本項目中,需求為批量下載某一批次文件。使用zip在服務(wù)器壓縮文件,之后將文件下載到客戶機(jī)。
網(wǎng)上查詢,使用java自帶的文件輸出類不能解決壓縮文件中文件名亂碼的問題。解決方法:使用ant.jar包,創(chuàng)建壓縮文件時,可以設(shè)置文件的編碼格式,文件名亂碼的問題就解決了。
html部分(可省略使用js構(gòu)建)
1
2
3
4
5
6
7
|
<form id= "uploadform" method= "post" enctype= "multipart/form-data" > <div class = "product-dl" > <input type= "hidden" name= "ordercode" /> <input type= "hidden" name= "datumtype" /> <a href= "javascript:void(0);" rel= "external nofollow" rel= "external nofollow" class = "btn" onclick= "batchdatumlistdownload()" >批量下載</a> </div> </form> |
js部分
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
//批量下載 function batchdatumlistdownload() { var param = {}; param.datumtype = $( "#datumtypeq" ).val(); if (param.datumtype == - 1 ) { param.datumtype = null ; //查詢所有 } param.ordercode = selfordercode; $( "#uploadform input[name=ordercode]" ).val(param.ordercode); $( "#uploadform input[name=datumtype]" ).val(param.datumtype); var form = $( "#uploadform" )[ 0 ]; form.action = "order/datumlist/batchdownloaddatumlist" ; form.method = "post" ; form.submit(); //表單提交 } |
后臺部分
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
|
public void batchdownloaddatumlist(datumlistvo datumlistvo, httpservletresponse response) { try { //查詢文件列表 list<datumlistvo> volist = datumlistservice.querydatumlists(datumlistvo); //壓縮文件 list<file> files = new arraylist<>(); for (datumlistvo vo : volist) { file file = new file(vo.getdatumurl()); files.add(file); } string filename = datumlistvo.getordercode() + "_" + datumlistvo.getdatumtype() + ".zip" ; //在服務(wù)器端創(chuàng)建打包下載的臨時文件 string globaluploadpath = "" ; string osname = system.getproperty( "os.name" ); if (osname.tolowercase().indexof( "windows" ) >= 0 ) { globaluploadpath = globalkeys.getstring(globalkeys.windows_upload_path); } else if (osname.tolowercase().indexof( "linux" ) >= 0 || osname.tolowercase().indexof( "mac" ) >= 0 ) { globaluploadpath = globalkeys.getstring(globalkeys.linux_upload_path); } string outfilepath = globaluploadpath + file.separator + filename; file file = new file(outfilepath); //文件輸出流 fileoutputstream outstream = new fileoutputstream(file); //壓縮流 zipoutputstream toclient = new zipoutputstream(outstream); //設(shè)置壓縮文件內(nèi)的字符編碼,不然會變成亂碼 toclient.setencoding( "gbk" ); ziputil.zipfile(files, toclient); toclient.close(); outstream.close(); ziputil.downloadzip(file, response); } catch (exception e) { e.printstacktrace(); } } |
其中ziputil.java
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
|
/** * 壓縮文件列表中的文件 * * @param files * @param outputstream * @throws ioexception */ public static void zipfile(list files, zipoutputstream outputstream) throws ioexception, servletexception { try { int size = files.size(); //壓縮列表中的文件 for ( int i = 0 ; i < size; i++) { file file = (file) files.get(i); try { zipfile(file, outputstream); } catch (exception e) { continue ; } } } catch (exception e) { throw e; } } /** * 將文件寫入到zip文件中 * * @param inputfile * @param outputstream * @throws exception */ public static void zipfile(file inputfile, zipoutputstream outputstream) throws ioexception, servletexception { try { if (inputfile.exists()) { if (inputfile.isfile()) { fileinputstream instream = new fileinputstream(inputfile); bufferedinputstream binstream = new bufferedinputstream(instream); zipentry entry = new zipentry(inputfile.getname()); outputstream.putnextentry(entry); final int max_byte = 10 * 1024 * 1024 ; //最大的流為10m long streamtotal = 0 ; //接受流的容量 int streamnum = 0 ; //流需要分開的數(shù)量 int leavebyte = 0 ; //文件剩下的字符數(shù) byte [] inoutbyte; //byte數(shù)組接受文件的數(shù)據(jù) streamtotal = binstream.available(); //通過available方法取得流的最大字符數(shù) streamnum = ( int ) math.floor(streamtotal / max_byte); //取得流文件需要分開的數(shù)量 leavebyte = ( int ) streamtotal % max_byte; //分開文件之后,剩余的數(shù)量 if (streamnum > 0 ) { for ( int j = 0 ; j < streamnum; ++j) { inoutbyte = new byte [max_byte]; //讀入流,保存在byte數(shù)組 binstream.read(inoutbyte, 0 , max_byte); outputstream.write(inoutbyte, 0 , max_byte); //寫出流 } } //寫出剩下的流數(shù)據(jù) inoutbyte = new byte [leavebyte]; binstream.read(inoutbyte, 0 , leavebyte); outputstream.write(inoutbyte); outputstream.closeentry(); //closes the current zip entry and positions the stream for writing the next entry binstream.close(); //關(guān)閉 instream.close(); } } else { throw new servletexception( "文件不存在!" ); } } catch (ioexception e) { throw e; } } /** * 下載打包的文件 * * @param file * @param response */ public static void downloadzip(file file, httpservletresponse response) { try { // 以流的形式下載文件。 bufferedinputstream fis = new bufferedinputstream( new fileinputstream(file.getpath())); byte [] buffer = new byte [fis.available()]; fis.read(buffer); fis.close(); // 清空response response.reset(); outputstream toclient = new bufferedoutputstream(response.getoutputstream()); response.setcontenttype( "application/octet-stream" ); response.setheader( "content-disposition" , "attachment;filename=" + file.getname()); toclient.write(buffer); toclient.flush(); toclient.close(); file.delete(); //將生成的服務(wù)器端文件刪除 } catch (ioexception ex) { ex.printstacktrace(); } } |
以上基本滿足文件上傳下載所需。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/qq_37878879/article/details/77197448