在這里使用了基于servlet的文件異步上傳,好了廢話不多說,直接上代碼了。。。
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
|
package com.future.zfs.util; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; 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.FileUploadBase.SizeLimitExceededException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; @SuppressWarnings ( "serial" ) public class FileUploadServlet extends HttpServlet { final long MAX_SIZE = 10 * 1024 * 1024 ; // 設置上傳文件最大為 10M // 允許上傳的文件格式的列表 final String[] allowtype = new String[] { "jpg" , "jpeg" , "gif" , "txt" , "doc" , "docx" , "mp3" , "wma" , "m4a" , "xls" }; public FileUploadServlet() { super (); } public void destroy() { super .destroy(); } @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType( "text/html" ); // 設置字符編碼為UTF-8, 這樣支持漢字顯示 response.setCharacterEncoding( "UTF-8" ); // 實例化一個硬盤文件工廠,用來配置上傳組件ServletFileUpload DiskFileItemFactory dfif = new DiskFileItemFactory(); dfif.setSizeThreshold( 4096 ); // 設置上傳文件時用于臨時存放文件的內存大小,這里是4K.多于的部分將臨時存在硬盤 dfif.setRepository( new File(request.getRealPath( "/" ) + "uploadtemp" )); // 設置存放臨時文件的目錄,web根目錄下的uploadtemp目錄 // 用以上工廠實例化上傳組件 ServletFileUpload sfu = new ServletFileUpload(dfif); // 設置最大上傳尺寸 sfu.setSizeMax(MAX_SIZE); PrintWriter out = response.getWriter(); // 從request得到 所有 上傳域的列表 List fileList = null ; try { fileList = sfu.parseRequest(request); } catch (FileUploadException e) { // 處理文件尺寸過大異常 if (e instanceof SizeLimitExceededException) { out.println( "{message:'文件尺寸超過規定大小:" +MAX_SIZE+ "字節'}" ); return ; } e.printStackTrace(); } // 沒有文件上傳 if (fileList == null || fileList.size() == 0 ) { out.println( "{message:'請選擇上傳文件'}" ); return ; } // 得到所有上傳的文件 Iterator fileItr = fileList.iterator(); // 循環處理所有文件 while (fileItr.hasNext()) { FileItem fileItem = null ; String path = null ; long size = 0 ; // 得到當前文件 fileItem = (FileItem) fileItr.next(); // 忽略簡單form字段而不是上傳域的文件域(<input type="text" />等) if (fileItem == null || fileItem.isFormField()) { continue ; } // 得到文件的完整路徑 path = fileItem.getName(); // 得到文件的大小 size = fileItem.getSize(); if ( "" .equals(path) || size == 0 ) { out.println( "{message:'請選擇上傳文件'}" ); return ; } // 得到去除路徑的文件名 String t_name = path.substring(path.lastIndexOf( "\\" ) + 1 ); // 得到文件的擴展名(無擴展名時將得到全名) String t_ext = t_name.substring(t_name.lastIndexOf( "." ) + 1 ); // 拒絕接受規定文件格式之外的文件類型 int allowFlag = 0 ; int allowedExtCount = allowtype.length; for (; allowFlag < allowedExtCount; allowFlag++) { if (allowtype[allowFlag].equals(t_ext)) break ; } if (allowFlag == allowedExtCount) { String message = "" ; for (allowFlag = 0 ; allowFlag < allowedExtCount; allowFlag++){ message+= "*." + allowtype[allowFlag] + " " ; } out.println( "{message:'請上傳以下類型的文件" +message+ "'}" ); return ; } long now = System.currentTimeMillis(); // 根據系統時間生成上傳后保存的文件名 String prefix = String.valueOf(now); // 保存的最終文件完整路徑,保存在web根目錄下的upload目錄下 String u_name = request.getRealPath( "/" ) + "upload/" + prefix + "." + t_ext; //原來的文件名 path=request.getRealPath( "/" ) + "upload/" +path; try { // 保存文件 fileItem.write( new File(path)); response.setStatus( 200 ); out.println( "{message:\"文件上傳成功. 已保存為: " + prefix + "." + t_ext + " 文件大小: " + size + "字節\"}" ); } catch (Exception e) { e.printStackTrace(); } } } } |
web.xml
1
2
3
4
5
6
7
8
|
< servlet > < servlet-name >fileUploadServlet</ servlet-name > < servlet-class >com.future.zfs.util.FileUploadServlet</ servlet-class > </ servlet > < servlet-mapping > < servlet-name >fileUploadServlet</ servlet-name > < url-pattern >/fileUploadServlet</ url-pattern > </ servlet-mapping > |
上傳頁面
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
|
<%@ page language= "java" contentType= "text/html; charset=UTF-8" pageEncoding= "UTF-8" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" > <html> <head> <meta http-equiv= "Content-Type" content= "text/html; charset=UTF-8" > <title>Insert title here</title> <script type= "text/javascript" src= "js/jquery.js" ></script> <script type= "text/javascript" src= "js/ajaxfileupload.js" ></script> <script type= "text/javascript" > function ajaxFileUpload() { $( "#loading" ) .ajaxStart( function (){ $( this ).show(); .ajaxComplete( function (){ $( this ).hide(); }); //文件上傳完成將圖片隱藏起來 $.ajaxFileUpload ( { url: 'fileUploadServlet' , //用于文件上傳的服務器端請求地址 secureuri: false , //一般設置為false fileElementId: 'file' , //文件上傳空間的id屬性 <input type="file" id="file" name="file" /> dataType: 'json' , //返回值類型 一般設置為json success: function (data, status) //服務器成功響應處理函數 { //alert(data.message);//從服務器返回的json中取出message中的數據,其中message為在struts2中定義的成員變量 $( '#myspan' ).html(data.message); if ( typeof (data.error) != 'undefined' ) { if (data.error != '' ) { //alert(data.error); $( '#myspan' ).html(data.message); } else { //alert(data.message); $( '#myspan' ).html(data.message); } } }, error: function (data, status, e) //服務器響應失敗處理函數 { //alert(e); $( '#myspan' ).html(e); } } ) return false ; } </script> </head> <body> <img src= "images/loading.gif" id= "loading" style= "display: none;" > <span style= "color: red;" id= "myspan" ></span><br/> <input type= "file" id= "file" name= "file" /> <br /> <input type= "button" value= "上傳" onclick= "return ajaxFileUpload();" > <a href= "fileDownLoadServlet?filename=通訊錄.xls" >哈哈,測試文件下載</a> </body> </html> |
需要注意的是:在使用ajaxFileUpload基于servlet上傳時需要設置response.setContentType("text/html");盡管dataType: 'json'設置為json仍要設置response.setContentType("text/html");否則獲取不到服務器端返回的數據以及會彈出一個對話框。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。