servlet實現文件上傳,預覽,下載和刪除,供大家參考,具體內容如下
一、準備工作:
1.1 文件上傳插件:uploadify;
1.2 文件上傳所需jar包:commons-fileupload-1.3.1.jar和commons-io-2.2.jar
1.3 將數據轉成json對象需要jar包:commons-beanutils-1.8.3.jar、commons-collections-3.2.1.jar、commons-lang-2.6.jar、commons-logging-1.1.3.jar、ezmorph-1.0.6.jar和json-lib-2.4-jdk15.jar
1.4 開發工具:我用的是eclipse,隨意
1.5 目錄結構
需要注意的是:變更uploadify.css文件中的取消文件上傳圖片的路徑
1
2
3
4
5
6
7
|
.uploadify-queue-item .cancel a { background: url( '../images/uploadify-cancel.png' ) 0 0 no-repeat; float : right; height: 16px; text-indent: -9999px; width: 16px; } |
二、代碼展示
2.1 客戶端代碼設計
jsp部分
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
|
<%@ page language= "java" import = "java.util.*" pageencoding= "utf-8" %> <!doctype html public "-//w3c//dtd html 4.01 transitional//en" > <html> <head> <title>演示-操作文件</title> <% @taglib uri= "http://java.sun.com/jsp/jstl/core" prefix= "c" %> <script type= "text/javascript" src= "<c:url value=" /js/jquery- 1.11 . 2 .min.js "/>" ></script> <script type= "text/javascript" src= "<c:url value=" /uploadify/js/jquery.uploadify- 3.2 . 1 .min.js "/>" ></script> <link href= "<c:url value=" rel= "external nofollow" /uploadify/css/uploadify.css "/>" type= "text/css" rel= "stylesheet" /> <script type= "text/javascript" >var baseurl = '<%=request.getcontextpath()%>' ;</script> <script type= "text/javascript" src= "<c:url value=" /index.js "/>" ></script> <style type= "text/css" > /* 上傳、取消上傳按鈕style start */ .button { width: 80px; margin: 3px 1px 0 5px; padding: 0 10px; background-color: #16a0d3; border: none; display: inline-block; font-family: "microsoft yahei"; font-size: 14px; cursor: pointer; height: 30px; line-height: 30px; color: #fff; border-radius: 5px; text-decoration:none; text-align:center; } .buttonover { width: 80px; margin: 3px 1px 0 5px; padding: 0 10px; background-color: #117ea6; border: none; display: inline-block; font-family: "microsoft yahei"; font-size: 14px; cursor: pointer; height: 30px; line-height: 30px; color: #fff; border-radius: 5px; text-decoration:none; text-align:center; } /* end 上傳、取消上傳按鈕style */ </style> </head> <body> <!-- 文件上傳 --> <div id= "file_upload" ></div> <div id= "ctrlupload" style= "display:none;" > <a href= "javascript:;" rel= "external nofollow" rel= "external nofollow" rel= "external nofollow" onclick= "$('#file_upload').uploadify('upload', '*');" class = "button" onmouseover= "javascript:this.classname='buttonover'" onmouseout= "javascript:this.classname='button'" > 上傳所有 </a> <a href= "javascript:;" rel= "external nofollow" rel= "external nofollow" rel= "external nofollow" onclick= "$('#file_upload').uploadify('cancel', '*');$('#ctrlupload').hide();" class = "button" onmouseover= "javascript:this.classname='buttonover'" onmouseout= "javascript:this.classname='button'" > 取消上傳 </a> </div> <table border= 1 style= "border-collapse: collapse;" id= "tablefiles" > <thead> <th>序號</th> <th>文件名</th> <th>文件預覽</th> <th>文件下載</th> <th>文件刪除</th> </thead> <tbody></tbody> </table> </body> </html> |
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
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
|
var operatefile = new operatefile(); window.onload = function() { operatefile.init(); } /** * 對文件進行操作 * @returns */ function operatefile() { var object = this ; /** * 初始化操作: */ this .init = function() { // 隊列中的文件數 var selectedcount = 0 ; $( '#file_upload' ).uploadify({ 'method' : 'get' , // 默認值post,設置成get是為了向后臺傳遞自定義的參數 'auto' : false , // 設置為true當選擇文件后就直接上傳了,為false需要點擊上傳按鈕才上傳。默認值為true 'buttontext' : '添加文件' , // 按鈕文本 'filetypeexts' : '*.gif; *.jpg; *.png;*.pdf;*.zip;' , // 限制上傳文件類型,默認值沒有限制(*.*) 'filetypedesc' : '請選擇gif jpg png pdf zip類型的文件' , // 這個屬性值必須設置filetypeexts屬性后才有效,用來設置選擇文件對話框中的提示文本,默認值:all files 'swf' : baseurl + '/uploadify/flash/uploadify.swf' , // flash文件路徑(幫助我們與后端交互數據) 'uploader' : baseurl + '/uploadfile.do' , // 處理文件上傳請求地址 'formdata' : { 'param1' : '測試文件上傳' }, // 請求參數:上傳每個文件的同時提交到服務器的額外數據 'ondialogclose' : function(queuedata) { // 獲取該隊列中有多少個要上傳的文件 var queuesize = $( '#file_upload-queue' ).children( 'div' ).length; if (queuesize > 0 ) { $( '#ctrlupload' ).show(); } }, 'onuploadsuccess' : function(file, data, response) { // 上傳成功 // 將josn字符串轉換成json對象 data = eval( '(' + data + ')' ); // 獲取頁面上文件展示table 有多少行 var rowslength = $( '#tablefiles' )[ 0 ].rows.length; // 設置查看文件所需參數 var param = "filename=" + data.filename; // 查看文件請求地址 var viewurl = baseurl + '/viewfile.do?' + param; // 下載文件請求地址 var downloadurl = baseurl + '/downloadfile.do?' + param; // 拼接一行tr var trtemplate = '<tr>' + '<td>' + rowslength + '</td>' + '<td>' + file.name // 仍展示原文件名 + '</td>' + '<td>' + '<a href="' + viewurl + '" rel="external nofollow" target="_blank">點擊預覽</a>' + '<input type="hidden" name="imgaddress" value="' + data.filename + '"/>' + '</td>' + '<td>' + '<a href="' + downloadurl + '" rel="external nofollow" >點擊下載</a>' + '</td>' + '<td>' + '<a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="operatefile.deletefile(\'' + data.filename + '\',' + rowslength + ');">點擊刪除</a>' + '</td>' + '</tr>' ; $( '#tablefiles' ).append(trtemplate); }, 'onuploaderror' : function(file, errorcode, errormsg, errorstring) { // 上傳失敗 } }); } /** * 刪除文件 * @param 文件名 */ this .deletefile = function(filename,rowindex) { // 設置刪除文件所需參數 var param = "filename=" + filename; // 刪除文件請求地址 var deleteurl = baseurl + '/deletefile.do?' + param; $.get( deleteurl, function(msg) { alert(msg); if ( "刪除失??!" != msg) { // 刪除該行記錄 $( '#tablefiles' )[ 0 ].deleterow(rowindex); } } ); } } |
2.2 服務器端代碼設計
文件上傳代碼(fileupload.javae文件)
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
157
158
159
160
|
package controller.filehandler; import java.io.file; import java.io.ioexception; import java.io.printwriter; import java.util.hashmap; import java.util.iterator; import java.util.list; import java.util.map; import javax.servlet.servletcontext; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import org.apache.commons.fileupload.fileitem; import org.apache.commons.fileupload.fileuploadexception; import org.apache.commons.fileupload.disk.diskfileitemfactory; import org.apache.commons.fileupload.servlet.servletfileupload; import net.sf.json.jsonobject; public class fileupload extends httpservlet { private static final long serialversionuid = 1l; protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { this .dopost(request, response); } /** * 處理文件上傳的post * @precaution 下方的類名出自包import org.apache.commons.fileupload.* */ protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { // 1.設置參數編碼 request.setcharacterencoding( "utf-8" ); // 設置響應數據字符集 response.setcharacterencoding( "utf-8" ); // 設置響應數據格式 // response.setcontenttype("application/json; charset=utf-8"); printwriter out = response.getwriter(); // 2.創建文件上傳處理工廠 diskfileitemfactory factory = new diskfileitemfactory(); // 3.設置臨時文件存放地點 // 3.1獲取當前web應用程序對象(web容器在啟動時,它會為每個web應用程序都創建一個對應的servletcontext對象,它代表當前web應用) servletcontext servletcontext = this .getservletconfig().getservletcontext(); // 3.2獲取服務器的臨時目錄(tomcat、weblogic) // d:\programfiles(x86)\apache\tomcat\apache-tomcat-7.0.40-x86\work\catalina\localhost\demo file repository = (file) servletcontext.getattribute( "javax.servlet.context.tempdir" ); // 3.3臨時文件將會存儲在該目錄下 factory.setrepository(repository); // 4.創建文件上傳處理器 servletfileupload upload = new servletfileupload(factory); // 5.判斷請求類型是否為文件上傳類型 boolean multipartcontent = upload.ismultipartcontent(request); map<string, string> mapdata = new hashmap<string, string>(); // 返回信息 string msg = "" ; // 錯誤信息 string errormsg = "" ; // 文件名 string filename = "" ; if (multipartcontent) { try { // 獲取請求參數 string param = request.getparameter( "param1" ); system.out.println(param); // 6.解析請求信息 list<fileitem> items = upload.parserequest(request); // 7.對所有請求信息進行判斷 iterator<fileitem> iter = items.iterator(); while (iter.hasnext()) { fileitem item = iter.next(); // 信息為文件格式 if (!item.isformfield()) { filename = processuploadedfile(param, item); msg = "上傳成功!" ; } } } catch (fileuploadexception e) { e.printstacktrace(); msg = "上傳失??!" ; errormsg = e.getmessage(); } } else { msg = "form表單類型不是multipart/form-data,無法上傳!" ; } mapdata.put( "msg" , msg); mapdata.put( "errormsg" , errormsg); mapdata.put( "filename" , filename); // 將map轉成json jsonobject jsondata = jsonobject.fromobject(mapdata); // 返回客戶端信息 out.print(jsondata.tostring()); } /** * 處理上傳的文件 * @param org_id * @param order * @param item */ @suppresswarnings ( "unused" ) private string processuploadedfile(string param, fileitem item) { // process a file upload string fieldname = item.getfieldname(); // 默認值為filedata // 獲取文件名 string filename = item.getname(); // 內容類型:application/octet-stream string contenttype = item.getcontenttype(); boolean isinmemory = item.isinmemory(); // 獲取文件大小 long sizeinbytes = item.getsize(); // 1.指定文件上傳的根路徑 string path = this .getservletcontext().getrealpath( "/web-inf/uploadfiles" ); // 2.路徑構成:/uploadfile/filename // todo 可以自定義文件存放路徑 // 3.根據路徑批量創建文件夾 file filedirectories = new file(path); // 目錄不存在時,再創建 if (!filedirectories.exists()) { filedirectories.mkdirs(); // 所有的文件夾都創建成功才返回true } // 4.文件名格式校驗(文件名中不能包含#號) int index = filename.indexof( "#" ); if (index > - 1 ) { filename = filename.replace( '#' , '_' ); } // todo 可以對文件名進行重命名 // 5.在指定路徑下創建指定名稱的文件 file uploadedfile = new file(path + "/" + filename); // 6.判斷該文件是否已存在 if (!uploadedfile.exists()) { try { // 使用了這個方法寫入文件,臨時文件會被系統自動刪除 item.write(uploadedfile); } catch (exception e) { e.printstacktrace(); } } // 返回重名后的文件名 return filename; } /** * 處理信息為普通的格式 * @param item */ private void processformfield(fileitem item) { // process a regular form field if (item.isformfield()) { string name = item.getfieldname(); string value = item.getstring(); } } } |
文件查看代碼(fileview.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
|
package controller.filehandler; import java.io.bufferedinputstream; import java.io.bufferedoutputstream; import java.io.fileinputstream; import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import javax.servlet.servletcontext; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; public class fileview extends httpservlet { private static final long serialversionuid = 1l; // 設定輸出的類型 private static final string gif = "image/gif;charset=utf-8" ; private static final string jpg = "image/jpeg;charset=utf-8" ; private static final string png = "image/png;charset=utf-8" ; private static final string pdf = "application/pdf;charset=utf-8" ; private static final string zip = "application/zip;charset=utf-8" ; protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { this .dopost(request, response); } /** * 處理文件查看的post * @throws ioexception * @precaution 下方的類名出自包import org.apache.commons.fileupload.* */ protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { // 文件流 inputstream is = null ; // 輸入緩沖流 bufferedinputstream bis = null ; // 得到輸出流 outputstream output = null ; // 輸出緩沖流 bufferedoutputstream bos = null ; // 1.設置參數編碼 request.setcharacterencoding( "utf-8" ); // 2.設置響應數據字符集 response.setcharacterencoding( "utf-8" ); // 3.獲取客戶端請求參數:文件名 string filename = request.getparameter( "filename" ); // 4.重置response response.reset(); // 5.設置響應數據格式 if (filename.endswith( ".gif" )) { response.setcontenttype(gif); } else if (filename.endswith( ".jpg" )) { response.setcontenttype(jpg); } else if (filename.endswith( ".png" )) { response.setcontenttype(png); } else if (filename.endswith( ".pdf" )) { response.setcontenttype(pdf); } else if (filename.endswith( ".gif" )) { response.setcontenttype(gif); } else if (filename.endswith( ".zip" )) { response.setcontenttype(zip); } string filepath = "web-inf/uploadfiles/" + filename; // 獲取當前web應用程序 servletcontext webapp = this .getservletcontext(); // 6.獲取指定文件上傳的真實路徑 filepath = webapp.getrealpath(filepath); // 7.讀取目標文件,通過response將目標文件寫到客戶端 is = new fileinputstream(filepath); bis = new bufferedinputstream(is); output = response.getoutputstream(); bos = new bufferedoutputstream(output); byte data[] = new byte [ 1024 ]; // 緩沖字節數 int size = bis.read(data); while (size != - 1 ) { bos.write(data, 0 , size); size = bis.read(data); } // 關閉流 bis.close(); bos.flush(); // 清空輸出緩沖流 bos.close(); output.close(); } } |
文件下載代碼(filedownload.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
|
package controller.filehandler; import java.io.fileinputstream; import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; public class filedownload extends httpservlet { private static final long serialversionuid = 1l; protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { this .dopost(request, response); } /** * 處理文件下載的post * @throws ioexception */ protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { // 1.設置參數編碼 request.setcharacterencoding( "utf-8" ); // 設置響應數據字符集 response.setcharacterencoding( "utf-8" ); // 1.獲得請求文件名 string filename = request.getparameter( "filename" ); // 2.設置文件mime類型(指定要返回內容的類型) response.setcontenttype(getservletcontext().getmimetype(filename)); // 3.設置content-disposition(指定下載該文件時的文件名) response.setheader( "content-disposition" , "attachment;filename=" + filename); // 4.讀取目標文件,通過response將目標文件寫到客戶端 // 4.1 獲取目標文件的絕對路徑 string filepath = "web-inf/uploadfiles/" + filename; filepath = this .getservletcontext().getrealpath(filepath); // 4.2 讀取文件 inputstream in = new fileinputstream(filepath); // 4.3 輸出文件 outputstream out = response.getoutputstream(); // 寫文件 int n; while ((n = in.read()) != - 1 ) { out.write(n); } in.close(); out.close(); } } |
文件刪除代碼(filedelete.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
|
package controller.filehandler; import java.io.file; import java.io.fileinputstream; import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; public class filedelete extends httpservlet { private static final long serialversionuid = 1l; protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { this .dopost(request, response); } /** * 處理文件下載的post * @throws ioexception */ protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { // 1.設置參數編碼 request.setcharacterencoding( "utf-8" ); // 設置響應數據字符集 response.setcharacterencoding( "utf-8" ); // 2.獲得請求文件名 string filename = request.getparameter( "filename" ); // 3.獲取該文件所在路徑 string filepath = "web-inf/uploadfiles/" + filename; filepath = this .getservletcontext().getrealpath(filepath); // 4.在指定路徑下創建指定名稱的文件 file deletefile = new file(filepath); boolean flag = false ; string msg = "" ; // 5.判斷該文件是否已存在 if (deletefile.exists()) { flag = deletefile.delete(); if (flag) { msg = "刪除成功!" ; } else { msg = "刪除失??!" ; } } else { msg = "該文件不存在!" ; } // 6.返回客戶端操作信息 response.getwriter().print(msg); } } |
web.xml代碼
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
|
<?xml version= "1.0" encoding= "utf-8" ?> <web-app xmlns:xsi= "http://www.w3.org/2001/xmlschema-instance" xmlns= "http://java.sun.com/xml/ns/javaee" xsi:schemalocation= "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id= "webapp_id" version= "2.5" > <display-name>demo_uploadanddownload</display-name> <context-param> <param-name>webapprootkey</param-name> <param-value>uploadanddownload</param-value> </context-param> <!-- 處理文件的servlet --> <!-- 文件上傳 start --> <servlet> <servlet-name>upload</servlet-name> <!-- 配置處理文件上傳的java類 --> <servlet- class >controller.filehandler.fileupload</servlet- class > </servlet> <servlet-mapping> <servlet-name>upload</servlet-name> <!-- 設置文件上傳請求路徑 --> <url-pattern>/uploadfile. do </url-pattern> </servlet-mapping> <!-- end 文件上傳 --> <!-- 文件預覽 start --> <servlet> <servlet-name>view</servlet-name> <!-- 配置處理文件預覽的java類 --> <servlet- class >controller.filehandler.fileview</servlet- class > </servlet> <servlet-mapping> <servlet-name>view</servlet-name> <!-- 設置文件預覽請求路徑 --> <url-pattern>/viewfile. do </url-pattern> </servlet-mapping> <!-- end 文件預覽 --> <!-- 文件下載 start --> <servlet> <servlet-name>download</servlet-name> <!-- 配置處理文件下載的java類 --> <servlet- class >controller.filehandler.filedownload</servlet- class > </servlet> <servlet-mapping> <servlet-name>download</servlet-name> <!-- 設置文件下載請求路徑 --> <url-pattern>/downloadfile. do </url-pattern> </servlet-mapping> <!-- end 文件下載 --> <!-- 文件刪除 start --> <servlet> <servlet-name>delete</servlet-name> <!-- 配置處理文件刪除的java類 --> <servlet- class >controller.filehandler.filedelete</servlet- class > </servlet> <servlet-mapping> <servlet-name>delete</servlet-name> <!-- 設置文件刪除請求路徑 --> <url-pattern>/deletefile</url-pattern> </servlet-mapping> <!-- end 文件刪除 --> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file> default .html</welcome-file> <welcome-file> default .htm</welcome-file> <welcome-file> default .jsp</welcome-file> </welcome-file-list> </web-app> |
2.3 代碼優化
處理文件查看(fileview.java) ,設置響應文件類型,可以用下面這句話替換
response.setcontenttype(getservletcontext().getmimetype(filename) + ";charset=utf-8");
三、效果展示
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/Marydon20170307/p/7472294.html