后臺上傳方法
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
|
@RequestMapping (value = "/api_upload" , method = RequestMethod.POST) public @ResponseBody String upload(HttpServletRequest request,HttpServletResponse response) { //獲取上傳路徑 String uploadFilePath=ParameterConstants.UPLOAD_FILE_PATH; String storePath= "" ; MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; // 獲取前臺傳值 String[] folders = multipartRequest.getParameterValues( "path" ); String folder = "" ; if (folders != null ) { folder = folders[ 0 ]; storePath+=folder+ "/" ; } Map<String, MultipartFile> fileMap = multipartRequest.getFileMap(); SimpleDateFormat sdf = new SimpleDateFormat( "yyyyMM" ); String ymd = sdf.format( new Date()); storePath += ymd + "/" ; // 創建文件夾 File file = new File(uploadFilePath+storePath); if (!file.exists()) { file.mkdirs(); } String fileName = null ; String path = null ; for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) { // 上傳文件名 MultipartFile mf = entity.getValue(); fileName = mf.getOriginalFilename(); String uuid = UUID.randomUUID().toString().replaceAll( "\\-" , "" ); // 返回一個隨機UUID。 String suffix = fileName.indexOf( "." ) != - 1 ? fileName.substring( fileName.lastIndexOf( "." ), fileName.length()) : null ; String newFileName = uuid + (suffix != null ? suffix : "" ); // 構成新文件名。 File uploadFile = new File(uploadFilePath+storePath + newFileName); try { /** * 驗證上傳文件的合法性 */ CommonsMultipartFile cmf =(CommonsMultipartFile)mf; boolean isValid=CheckoutFileType.getUpFilelegitimacyFlag(cmf.getFileItem(), ".jpg.gif.png.jpeg" ); if (!isValid){ return null ; } FileCopyUtils.copy(mf.getBytes(), uploadFile); storePath = storePath + newFileName; } catch (IOException e) { e.printStackTrace(); } } return storePath; } |
文件合法性驗證類
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
|
package com.kaiyuan.common.util; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import org.apache.commons.fileupload.FileItem; /** * @Description: 處理上傳附件,校驗是否合法 在服務器端判斷文件類型的問題,故用獲取文件頭的方式, * 直接讀取文件的前幾個字節,來判斷上傳文件是否符合格式 */ public class CheckoutFileType { // 記錄各個文件頭信息及對應的文件類型 public static Map<String, String> mFileTypes = new HashMap<String, String>(); // 所有合法的文件后綴 public static String res_fileType = ".jpg.gif.png.jpeg" ; static { // images mFileTypes.put( "FFD8FFE0" , ".jpg" ); mFileTypes.put( "89504E47" , ".png" ); mFileTypes.put( "47494638" , ".gif" ); mFileTypes.put( "49492A00" , ".tif" ); mFileTypes.put( "424D" , ".bmp" ); // PS和CAD mFileTypes.put( "38425053" , ".psd" ); mFileTypes.put( "41433130" , ".dwg" ); // CAD mFileTypes.put( "252150532D41646F6265" , ".ps" ); // 辦公文檔類 mFileTypes.put( "D0CF11E0" , ".doc" ); // ppt、doc、xls mFileTypes.put( "504B0304" , ".docx" ); // pptx、docx、xlsx /** 注意由于文本文檔錄入內容過多,則讀取文件頭時較為多變-START **/ mFileTypes.put( "0D0A0D0A" , ".txt" ); // txt mFileTypes.put( "0D0A2D2D" , ".txt" ); // txt mFileTypes.put( "0D0AB4B4" , ".txt" ); // txt mFileTypes.put( "B4B4BDA8" , ".txt" ); // 文件頭部為漢字 mFileTypes.put( "73646673" , ".txt" ); // txt,文件頭部為英文字母 mFileTypes.put( "32323232" , ".txt" ); // txt,文件頭部內容為數字 mFileTypes.put( "0D0A09B4" , ".txt" ); // txt,文件頭部內容為數字 mFileTypes.put( "3132330D" , ".txt" ); // txt,文件頭部內容為數字 /** 注意由于文本文檔錄入內容過多,則讀取文件頭時較為多變-END **/ mFileTypes.put( "7B5C727466" , ".rtf" ); // 日記本 mFileTypes.put( "255044462D312E" , ".pdf" ); // 視頻或音頻類 mFileTypes.put( "3026B275" , ".wma" ); mFileTypes.put( "57415645" , ".wav" ); mFileTypes.put( "41564920" , ".avi" ); mFileTypes.put( "4D546864" , ".mid" ); mFileTypes.put( "2E524D46" , ".rm" ); mFileTypes.put( "000001BA" , ".mpg" ); mFileTypes.put( "000001B3" , ".mpg" ); mFileTypes.put( "6D6F6F76" , ".mov" ); mFileTypes.put( "3026B2758E66CF11" , ".asf" ); // 壓縮包 mFileTypes.put( "52617221" , ".rar" ); mFileTypes.put( "1F8B08" , ".gz" ); // 程序文件 mFileTypes.put( "3C3F786D6C" , ".xml" ); mFileTypes.put( "68746D6C3E" , ".html" ); mFileTypes.put( "7061636B" , ".java" ); mFileTypes.put( "3C254020" , ".jsp" ); mFileTypes.put( "4D5A9000" , ".exe" ); mFileTypes.put( "44656C69766572792D646174653A" , ".eml" ); // 郵件 mFileTypes.put( "5374616E64617264204A" , ".mdb" ); // Access數據庫文件 mFileTypes.put( "46726F6D" , ".mht" ); mFileTypes.put( "4D494D45" , ".mhtml" ); } /** * 根據文件的輸入流獲取文件頭信息 * * @param filePath * 文件路徑 * @return 文件頭信息 */ public static String getFileType(InputStream is) { byte [] b = new byte [ 4 ]; if (is != null ) { try { is.read(b, 0 , b.length); } catch (IOException e) { e.printStackTrace(); } } return mFileTypes.get(getFileHeader(b)); } /** * 根據文件轉換成的字節數組獲取文件頭信息 * * @param filePath * 文件路徑 * @return 文件頭信息 */ public static String getFileHeader( byte [] b) { String value = bytesToHexString(b); return value; } /** * 將要讀取文件頭信息的文件的byte數組轉換成string類型表示 下面這段代碼就是用來對文件類型作驗證的方法, * 將字節數組的前四位轉換成16進制字符串,并且轉換的時候,要先和0xFF做一次與運算。 * 這是因為,整個文件流的字節數組中,有很多是負數,進行了與運算后,可以將前面的符號位都去掉, * 這樣轉換成的16進制字符串最多保留兩位,如果是正數又小于10,那么轉換后只有一位, * 需要在前面補0,這樣做的目的是方便比較,取完前四位這個循環就可以終止了 * * @param src要讀取文件頭信息的文件的byte數組 * @return 文件頭信息 */ private static String bytesToHexString( byte [] src) { StringBuilder builder = new StringBuilder(); if (src == null || src.length <= 0 ) { return null ; } String hv; for ( int i = 0 ; i < src.length; i++) { // 以十六進制(基數 16)無符號整數形式返回一個整數參數的字符串表示形式,并轉換為大寫 hv = Integer.toHexString(src[i] & 0xFF ).toUpperCase(); if (hv.length() < 2 ) { builder.append( 0 ); } builder.append(hv); } System.out.println( "獲取文件頭信息:" + builder.toString()); return builder.toString(); } /** * 判斷上傳的文件是否合法 (一)、第一:檢查文件的擴展名, (二)、 第二:檢查文件的MIME類型 。 * * @param attachDoc * @return boolean */ public static boolean getUpFilelegitimacyFlag(FileItem attachDoc,String allowType) { boolean upFlag = false ; // 為真表示符合上傳條件,為假表標不符合 if (attachDoc != null ) { String attachName = attachDoc.getName(); System.out.println( "#######上傳的文件:" + attachName); if (! "" .equals(attachName) && attachName != null ) { /** 返回在此字符串中最右邊出現的指定子字符串的索引 **/ String sname = attachName .substring(attachName.lastIndexOf( "." )); /** 統一轉換為小寫 **/ sname = sname.toLowerCase(); /** 第一步:檢查文件擴展名,是否符合要求范圍 **/ if (allowType.indexOf(sname) != - 1 ) { upFlag = true ; } /** * 第二步:獲取上傳附件的文件頭,判斷屬于哪種類型,并獲取其擴展名 直接讀取文件的前幾個字節,來判斷上傳文件是否符合格式 * 防止上傳附件變更擴展名繞過校驗 ***/ if (upFlag) { byte [] b = new byte [ 4 ]; String req_fileType = null ; try { req_fileType = getFileType(attachDoc.getInputStream()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println( "///////用戶上傳的文件類型///////////" + req_fileType); /** 第三步:檢查文件擴展名,是否符合要求范圍 **/ if (req_fileType != null && ! "" .equals(req_fileType) && ! "null" .equals(req_fileType)) { /** 第四步:校驗上傳的文件擴展名,是否在其規定范圍內 **/ if (allowType.indexOf(req_fileType) != - 1 ) { upFlag = true ; } else { upFlag = false ; } } else { /** 特殊情況校驗,如果用戶上傳的擴展名為,文本文件,則允許上傳-START **/ if (sname.indexOf( ".txt" ) != - 1 ) { upFlag = true ; } else { upFlag = false ; } /** 特殊情況校驗,如果用戶上傳的擴展名為,文本文件,則允許上傳-END **/ } } } } return upFlag; } /** * 主函數,測試用 * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { // final String fileType = getFileType("D:/BICP-HUAWEI.mht"); FileInputStream is = null ; String value = null ; String filePath = "e:/aa/c.txt" ; try { is = new FileInputStream(filePath); byte [] b = new byte [ 4 ]; is.read(b, 0 , b.length); value = bytesToHexString(b); } catch (Exception e) { } finally { if ( null != is) { try { is.close(); } catch (IOException e) { } } } System.out.println(value); } } |
前端上傳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
|
$(document).ready( function () { new TextMagnifier({ inputElem: '#bankCardNo' , align: 'top' , splitType: [4,4,4,5,5], delimiter: ' ' }); $( '#file_upload' ).uploadify({ 'formData' : { 'path' : '/uploadfilePath' , }, 'swf' : '${pageContext.request.contextPath}/js/upload/uploadify.swf' , 'uploader' : getBasePath()+ '/upload/api_upload;jsessionid=${pageContext.session.id}' , 'cancelImg' : '${pageContext.request.contextPath}/js/upload/uploadify-cancel.png' , 'buttonText' : '上傳' , 'auto' : true , 'multi' : true , 'uploadLimit' :100, 'removeCompleted' : true , 'fileTypeExts' : '*.jpg;*.gif;*.png;*.jpeg;' , 'fileSizeLimit' : '2MB' , 'fileTypeDesc' : '上傳' , 'onUploadSuccess' : function (file,data,response) { if (data!= null && data.length>0){ var uploadFiles=$( "#tickets" ).val().split( ',' ); var uploadFileSize=uploadFiles.length; if (uploadFileSize>5){ layer.msg( "最多上傳5張圖片" ); return ; } addTickets(data); /* layer.ready(function(){ layer.photos({ photos: '#imgShow', shade:0.5 }); }); */ } else { layer.msg( "上傳失敗" ); } isUploadSuccess= true ; }, 'onUploadError' : function (file, errorCode, errorMsg, errorString) { if (errorString.indexOf( 'The upload limit has been reached' )){ layer.msg(errorString); } }, 'onSelect' : function (file) { //alert('The file ' + file.name + ' was added to the queue.'); isUploadSuccess= false ; }, 'onSelectError' : function (file, errorCode, errorMsg){ switch (errorCode){ case -110: layer.msg( "文件大小超過了2M" ); break ; case -100: layer.msg( "最多上傳5張圖片" ); break ; default : layer.msg(errorMsg); } }, 'onDialogClose' : function (queueData) { var uploadFiles=$( "#tickets" ).val().split( ',' ); var uploadFileSize=uploadFiles.length; if (uploadFileSize>5){ layer.msg( "最多上傳5張圖片" ); queueData.filesSelected=0 return false ; } } }); onQuery(); }); |
以上所述是小編給大家介紹的uploadify上傳及后臺文件合法性驗證的代碼解析,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://blog.csdn.net/riapgypm/article/details/53096659