在工作中要求將圖片上傳至本地,如下代碼將介紹如何將圖片上傳至本地
準(zhǔn)備工作:
環(huán)境:eclipse4.5-x64,jdk1.7-x64,maven3
tomcat服務(wù)器配置圖片上傳映射:
上傳至本地服務(wù)器配置文件:image.properties
1
2
3
4
5
6
7
8
9
10
11
|
#\u672c\u5730\u670d\u52a1\u5668\u56fe\u7247\u4fdd\u5b58\u8def\u5f84 imagepath=/mall/upload/image/ #\u56fe\u7247\u540e\u7f00\u540d file_extend_name=gif,jpg,jpeg,png,bmp #\u672c\u5730\u670d\u52a1\u5668\u89c6\u9891\u5b58\u50a8\u5730\u5740 mediapath=/mall/upload/media/ #\u89c6\u9891\u540e\u7f00\u540d media_extend_name=mp4 |
controlle:uploadutil.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
|
/** * 文件上傳工具類 * @author sang */ @controller public class uploadutil { /** 記錄日志對象 */ private static final mylogger logger = new mylogger(uploadutil. class ); /**圖片格式錯誤信息*/ private static final string loggerinfo1 = "的圖片不符合限制" ; /** * 備注: * uploadimglocal,uploadimgoss,ossconfmapper均是靜態(tài)成員變量 * 則添加注解注意只能用@autowired且get,set方法不能有static否則報錯 * */ /**文件上傳:本地,注意*/ private static uploadimglocal uploadimglocal; /**文件上傳:oss對象 */ private static uploadimgoss uploadimgoss; /**oss配置查詢 */ private static ossconfmapper ossconfmapper; public uploadimglocal getuploadimglocal() { return uploadimglocal; } @autowired public void setuploadimglocal(uploadimglocal uploadimglocal) { uploadutil.uploadimglocal = uploadimglocal; } public uploadimgoss getuploadimgoss() { return uploadimgoss; } @autowired public void setuploadimgoss(uploadimgoss uploadimgoss) { uploadutil.uploadimgoss = uploadimgoss; } public ossconfmapper getossconfmapper() { return ossconfmapper; } @autowired public void setossconfmapper(ossconfmapper ossconfmapper) { uploadutil.ossconfmapper = ossconfmapper; } /** * 上傳文件:去除85這個寬度 * @param mufile 上傳文件 * @param req * @return map 返回中 key值{0,1,2,oldimg} 0小圖 1中圖 2大圖 oldimg原圖 */ public static synchronized map<string, string> uploadfile(multipartfile mufile,httpservletrequest req) { map<string, string> map = null ; try { //查詢oss啟用狀態(tài)的配置信息 ossconf ossconf=ossconfmapper.findbyossstatus(); if (mufile != null && mufile.getsize()> 0 && ossconf!= null ) { //檢查上傳的圖片的大小和擴展名 if (!uploadimgcommon.checkfileforspringupload(mufile)) { throw new runtimeexception( "上傳" + mufile.getoriginalfilename() + loggerinfo1); } //oss類型0本地1阿里云2京東云 string osstype=ossconf.getosstype(); if ( "0" .equals(osstype)){ //上傳本地 map = uploadimglocal.uploadforabcsize(mufile); } else if ( "1" .equals(osstype) || "2" .equals(osstype)){ //上傳oss map=uploadimgoss.uploadforabcsize(mufile,ossconf); } } } catch (exception e) { e.printstacktrace(); logger.error( "上傳文件失敗" +e.getmessage(),e); } return map; } } |
類:uploadimglocal.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
|
/** * 上傳文件:本地 * @author somnus * */ @component ( "uploadimglocal" ) public class uploadimglocal { /** 記錄日志對象 */ private static final mylogger logger = new mylogger(uploadimglocal. class ); /**獲得當(dāng)前項目訪問的地址 */ private static string url; @resource (name = "syshelpermapper" ) private syshelpermapper syshelpermapper; /** * 上傳文件:去除85這個寬度 * 存儲原圖地址如:http://127.0.0.1:8080:/mall/upload/image/20170804/1501811601145.jpg * @param mufile * @return map 返回中 key值{0,1,2,oldimg} 0小圖 1中圖 2大圖 oldimg原圖 */ public map<string, string> uploadforabcsize(multipartfile mufile) { //封裝結(jié)果集 map<string, string> imgmap = new hashmap<string, string>(); //服務(wù)器本地保存圖片路徑 httpservletrequest request = ((servletrequestattributes) requestcontextholder.getrequestattributes()).getrequest(); //獲得當(dāng)前項目訪問的地址:http://127.0.0.1:8080 url=uploadimgcommon.gethttpandport(request); //獲取上傳文件的保存路徑:文件拼接地址:服務(wù)器本地保存路徑+文件名+后綴 string filenamess = uploadimgcommon.getpicnamepathsuffix(); try { file file = new file(filenamess); //轉(zhuǎn)存文件到指定的路徑 mufile.transferto(file); //獲取原圖地址 logger.info(uploadimgcommon.loggerinfo1 + (url+filenamess)); //存儲原圖地址如:/mall/upload/image/20170804/1501811601145.jpg imgmap.put(uploadimgcommon.oldimg, (url+filenamess)); //圖片處理:獲取寬度集合,去除85這個寬度[352, 56, 160] int [] widths = uploadimgcommon.getimgsetout85(syshelpermapper.selectimageset()); //給寬度集合升序排序 uploadimgcommon.sortwidth(widths); //[56,160,352] //縮放文件 file zoomfile= null ; for ( int i = 0 ; i < widths.length; i++){ //20171226新優(yōu)化:將指定尺寸圖片存儲至本地 //縮放文件名 string zoomfilename=uploadimgcommon.picpath + uploadimgcommon.prefix + uploadimgcommon.symbols + widths[i] + uploadimgcommon.suffix; //創(chuàng)建縮放文件 zoomfile= new file(zoomfilename); //轉(zhuǎn)存文件到指定的路徑 mufile.transferto(zoomfile); //獲取指定尺寸圖片地址:大圖352中160小56 logger.info(widths[i]+uploadimgcommon.loggerinfo2+(url + uploadimgcommon.picpath + uploadimgcommon.prefix + uploadimgcommon.symbols + widths[i] + uploadimgcommon.suffix)); imgmap.put(i + "" , (url + uploadimgcommon.picpath + uploadimgcommon.prefix + uploadimgcommon.symbols + widths[i] + uploadimgcommon.suffix)); } } catch (illegalstateexception e) { e.printstacktrace(); logger.error(uploadimgcommon.loggerinfo3, e); } catch (ioexception e) { e.printstacktrace(); logger.error(uploadimgcommon.loggerinfo3, e); } catch (exception e) { e.printstacktrace(); logger.error(uploadimgcommon.loggerinfo3, e); } return imgmap; } } |
公共方法:uploadimgcommon.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
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
|
package com.qianjiang.util.uploadutil; import java.io.file; import java.io.inputstream; import java.util.arrays; import java.util.date; import java.util.hashmap; import java.util.list; import java.util.properties; import javax.servlet.http.httpservletrequest; import org.apache.commons.fileupload.fileitem; import org.springframework.web.multipart.multipartfile; import com.qianjiang.manager.bean.imageset; import com.qianjiang.util.mylogger; import com.qianjiang.util.utildate; /** * 文件上傳公共方法 * @author somnus */ public class uploadimgcommon { /** 記錄日志對象 */ private static final mylogger logger = new mylogger(uploadimgcommon. class ); /**定義圖片*/ protected static final string image = "image" ; /**定義視頻*/ protected static final string media= "media" ; /**定義圖片上傳最大限制10mb*/ private static long maxsize = 10 * 1024 * 1024 ; /**定義視頻上傳最大限制500mb */ private static long mediamaxsize= 500 * 1024 * 1024 ; /**定義允許上傳文件擴展名 */ private static hashmap<string, string> extmap = new hashmap<string, string>(); /**文件保存路徑 */ protected static string picpath; /** 要保存的文件名 */ protected static string prefix; /**文件后綴 */ protected static string suffix; /**定位寬度集合循環(huán)次數(shù)*/ protected static final int three = 3 ; /**拼接圖片縮放特殊符號*/ protected static final string symbols= "@" ; /**圖片56縮放*/ protected static final int small = 56 ; /**設(shè)置imgmap中返回小圖key值*/ protected static final int smallimg= 0 ; /**原圖*/ protected static final string oldimg = "oldimg" ; protected static final string loggerinfo1 = "原圖地址:" ; protected static final string loggerinfo2 = "尺寸的圖片地址:" ; protected static final string loggerinfo3 = "圖片上傳,返回key值列表錯誤" ; //本地上傳圖片properties屬性值 protected static final string imagepath = "imagepath" ; //本地上傳視頻properties屬性值 protected static final string mediapath = "mediapath" ; /**初始化*/ static { //允許圖片擴展名 extmap.put(image, "gif,jpg,jpeg,png,bmp" ); //允許視頻擴展名 extmap.put(media, "mp4" ); } /** * 獲取上傳文件的保存路徑 * 文件拼接地址:服務(wù)器本地保存路徑+文件名+后綴 * @return 文件名(全路徑) */ public static string getpicnamepathsuffix() { string filename= "" ; try { //根據(jù)系統(tǒng)當(dāng)前時間生成上傳后保存的文件名 long now = system.currenttimemillis(); //文件名系統(tǒng)當(dāng)前時間如1501848484869 prefix = string.valueof(now); //文件路徑如:/mall/upload/image/20170804/ picpath = gethostandport().getproperty(imagepath) + utildate.todayformatstring( new date()) + "/" ; //根據(jù)真實路徑創(chuàng)建目錄文件 file picsavefile = new file(picpath); if (!picsavefile.exists()){ picsavefile.mkdirs(); } //文件的后綴 suffix = ".jpg" ; filename=picpath + prefix + suffix; logger.info( "創(chuàng)建文件成功,文件名:" +filename); } catch (exception e) { e.printstacktrace(); logger.error( "創(chuàng)建本地文件失敗" +e.getmessage(),e); } return filename; } /** * 上傳視頻存儲本地服務(wù)器 * 獲取上傳文件的保存名稱、服務(wù)器本地保存路徑、后綴,拼接成文件地址 * @return */ public static string getvideonamepathsuffix() { string filename= "" ; try { //根據(jù)系統(tǒng)當(dāng)前時間生成上傳后保存的文件名 long now = system.currenttimemillis(); //文件名系統(tǒng)當(dāng)前時間如1501848484869 prefix = string.valueof(now); //文件路徑如:/mall/upload/media/20170804/ picpath =gethostandport().getproperty(mediapath) + utildate.todayformatstring( new date()) + "/" ; //根據(jù)真實路徑創(chuàng)建目錄文件 file picsavefile = new file(picpath); if (!picsavefile.exists()){ picsavefile.mkdirs(); } //文件的后綴(默認為mp4格式) uploadimgcommon.suffix = ".mp4" ; filename=picpath + prefix + suffix; logger.info( "創(chuàng)建視頻文件成功,文件名:" +filename); } catch (exception e) { e.printstacktrace(); logger.error( "創(chuàng)建上傳視頻本地服務(wù)器地址失敗:" +e.getlocalizedmessage(), e); } return filename; } /** * 獲取寬度集合 * @return */ public static int [] getimgset(list<imageset> imgset) { int [] widths = new int [imgset.size()]; for ( int i = 0 ; i < imgset.size(); i++) { widths[i] = integer.parseint(imgset.get(i).getrulewidth()); } return widths; } /** * 獲取寬度集合,去除85這個寬度 * @param imgset * @return */ public static int [] getimgsetout85(list<imageset> imgset) { int [] widths = new int [three]; for ( int i = 0 ; i < imgset.size(); i++) { if ( "85" .equals(imgset.get(i).getrulewidth())) { if (i < 3 ) { i--; } continue ; } widths[i] = integer.parseint(imgset.get(i).getrulewidth()); } return widths; } /** * 給寬度集合升序排序 * @param widths */ public static void sortwidth( int [] widths) { for ( int i = 0 ; i < widths.length; i++) { for ( int j = i + 1 ; j < widths.length; j++) { int temp; if (widths[i] > widths[j]) { temp = widths[i]; widths[i] = widths[j]; widths[j] = temp; } } } } /** * 獲得當(dāng)前項目訪問的地址 * 比如http://127.0.0.1:8080 * @param request * @return 返回當(dāng)前項目訪問的地址 */ public static string gethttpandport(httpservletrequest request) { return request.getscheme() + "://" + request.getservername() + ":" + request.getserverport(); } /** * 讀取配置文件信息 * @return */ public static properties gethostandport() { properties p = new properties(); try { inputstream inputstream = uploadimgcommon. class .getclassloader().getresourceasstream( "config/image.properties" ); p.load(inputstream); } catch (exception e){ e.printstacktrace(); logger.error( "讀取properties屬性文件錯誤" +e.getmessage(),e); } return p; } /** * springmvc上傳:驗證上傳圖片的大小和擴展名 * @param mufile 上傳文件 * @return 驗證通過返回true,否則返回false */ public static boolean checkfileforspringupload(multipartfile mufile) { boolean bool = true ; // 檢查文件大小 if (mufile.getsize() > maxsize) { logger.error( "=============>上傳" + mufile.getoriginalfilename() + "文件大小超過限制" ); bool = false ; return bool; } string filename = mufile.getoriginalfilename(); //檢查擴展名 string fileext = filename.substring(filename.lastindexof( "." ) + 1 ).tolowercase(); if (!arrays.<string> aslist(extmap.get(image).split( "," )).contains(fileext)) { logger.error( "上傳文件" + mufile.getoriginalfilename() + "擴展名是不允許的擴展名。\n只允許" + extmap.get(image) + "格式。" ); bool = false ; return bool; } return bool; } /** * js引入kindeditor插件實現(xiàn)文件上傳 * 驗證上傳文件大小和擴展名 * @param file 上傳文件 * @return 驗證通過返回true,否則返回false */ public static boolean checkfileandmedia(fileitem file,string dirname) { boolean bool = true ; //文件大小 long filesize = file.getsize(); //文件名 string filename = file.getname(); //檢查文件大小 if (filesize > maxsize && filesize > mediamaxsize){ logger.error( "=============>上傳" + file.getfieldname() + "文件大小超過限制" ); bool = false ; return bool; } //檢查擴展名 string fileext = filename.substring(filename.lastindexof( "." ) + 1 ).tolowercase(); if (!arrays.<string>aslist(extmap.get(dirname).split( "," )).contains(fileext)){ logger.error( "上傳文件" + file.getfieldname() + "擴展名是不允許的擴展名。\n只允許" + extmap.get(dirname) + "格式。" ); bool = false ; return bool; } return bool; } } |
上傳成功后控制臺打印信息:
上傳成功后前臺展示效果:
原文鏈接:https://blog.csdn.net/u014079773/article/details/79763325