web uploader簡介
webuploader是由baidu webfe(fex)團隊開發的一個簡單的以html5為主,flash為輔的現代文件上傳組件。在現代的瀏覽器里面能充分發揮html5的優勢,同時又不摒棄主流ie瀏覽器,沿用原來的flash運行時,兼容ie6+,ios 6+, android 4+。兩套運行時,同樣的調用方式,可供用戶任意選用。采用大文件分片并發上傳,極大的提高了文件上傳效率。
我們這里使用官網的一個例子來實現我們個人頭像的上傳。
我們的重點是在spring boot項目中利用webuploader如何進行文件上傳,所以直接實現一個簡單的功能,僅供參考。
下面是一個從官網下載來的示例:帶剪裁的圖片上傳功能。
我們利用示例來改造項目中的個人頭像上傳。
效果看起來是這樣的:
首先我們來改造我們的webuploader示例代碼。
以下都是我項目中的部分代碼:
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
|
(function( factory ) { if ( !window.jquery ) { alert( 'jquery is required.' ) } jquery(function() { factory.call( null , jquery ); }); }) (function( $ ) { // ----------------------------------------------------- // ------------ start ---------------------------------- // ----------------------------------------------------- // --------------------------------- // --------- uploader ------------- // --------------------------------- var uploader = (function() { // -------setting------- // 如果使用原始大小,超大的圖片可能會出現 croper ui 卡頓,所以這里建議先縮小后再crop. var frame_width = 1600 ; var _ = webuploader; var uploader = _.uploader; var uploadercontainer = $( '.uploader-container' ); var uploader, file; if ( !uploader.support() ) { alert( 'web uploader 不支持您的瀏覽器!' ); throw new error( 'webuploader does not support the browser you are using.' ); } // hook, // 在文件開始上傳前進行裁剪。 uploader.register({ 'before-send-file' : 'cropimage' }, { cropimage: function( file ) { var data = file._cropdata, image, deferred; file = this .request( 'get-file' , file ); deferred = _.deferred(); image = new _.lib.image(); deferred.always(function() { image.destroy(); image = null ; }); image.once( 'error' , deferred.reject ); image.once( 'load' , function() { image.crop( data.x, data.y, data.width, data.height, data.scale ); }); image.once( 'complete' , function() { var blob, size; // 移動端 uc / qq 瀏覽器的無圖模式下 // ctx.getimagedata 處理大圖的時候會報 exception // index_size_err: dom exception 1 try { blob = image.getasblob(); size = file.size; file.source = blob; file.size = blob.size; file.trigger( 'resize' , blob.size, size ); deferred.resolve(); } catch ( e ) { console.log( e ); // 出錯了直接繼續,讓其上傳原始圖片 deferred.resolve(); } }); file._info && image.info( file._info ); file._meta && image.meta( file._meta ); image.loadfromblob( file.source ); return deferred.promise(); } }); return { init: function( selectcb ) { uploader = new uploader({ pick: { id: '#filepicker' , multiple: false }, // 設置用什么方式去生成縮略圖。 thumb: { quality: 70 , // 不允許放大 allowmagnify: false , // 是否采用裁剪模式。如果采用這樣可以避免空白內容。 crop: false }, // 禁掉分塊傳輸,默認是開起的。 chunked: false , // 禁掉上傳前壓縮功能,因為會手動裁剪。 compress: false , // filesinglesizelimit: 2 * 1024 * 1024, server: 'studentimgfileupload' , swf: $.trim($( "#base_url" ).val()) + '/static/webuploader/uploader.swf' , filenumlimit: 1 , // 只允許選擇圖片文件。 accept: { title: 'images' , // extensions: 'gif,jpg,jpeg,bmp,png', // mimetypes: 'image/*' extensions: 'jpg,jpeg,png' , //解決webuploader chrome 點擊上傳文件選擇框會延遲幾秒才會顯示 反應很慢 mimetypes: 'image/jpg,image/jpeg,image/png' //修改這行 } //formdata: {"authorization": localstorage.token}, //額外參數傳遞,可以沒有 // chunked: true, //分片 // chunksize: 10 * 1024 * 1024, //分片大小指定 // threads:1, //線程數量 // disableglobaldnd: true //禁用拖拽 // onerror: function() { // var args = [].slice.call(arguments, 0); // alert(args.join('\n')); // } }); uploader.on( 'filequeued' , function( _file ) { file = _file; uploader.makethumb( file, function( error, src ) { if ( error ) { alert( '不能預覽' ); return ; } selectcb( src ); }, frame_width, 1 ); // 注意這里的 height 值是 1,被當成了 100% 使用。 }); /** * 驗證文件格式以及文件大小 */ uploader.on( "error" , function (type) { if (type == "q_type_denied" ) { showinfo( "請上傳jpg、jepg、png、格式文件" ); } }); // 文件上傳成功,給item添加成功class, 用樣式標記上傳成功。 uploader.on( 'uploadsuccess' , function( file ) { showinfo( "上傳成功" ); }); // 文件上傳失敗,顯示上傳出錯。 uploader.on( 'uploaderror' , function( file ) { showinfo( "上傳失敗" ); }); }, crop: function( data ) { var scale = croper.getimagesize().width / file._info.width; data.scale = scale; file._cropdata = { x: data.x1, y: data.y1, width: data.width, height: data.height, scale: data.scale }; }, upload: function() { uploader.upload(); } } })(); // --------------------------------- // --------- crpper --------------- // --------------------------------- var croper = (function() { var container = $( '.cropper-wraper' ); var $image = container.find( '.img-container img' ); var btn = $( '.upload-btn' ); var isbase64supported, callback; $image.cropper({ aspectratio: 4 / 4 , preview: ".img-preview" , done: function(data) { // console.log(data); } }); function srcwrap( src, cb ) { // we need to check this at the first time. if (typeof isbase64supported === 'undefined' ) { (function() { var data = new image(); var support = true ; data.onload = data.onerror = function() { if ( this .width != 1 || this .height != 1 ) { support = false ; } } data.src = src; isbase64supported = support; })(); } if ( isbase64supported ) { cb( src ); } else { // otherwise we need server support. // convert base64 to a file. // $.ajax('', { // method: 'post', // data: src, // datatype:'json' // }).done(function( response ) { // if (response.result) { // cb( response.result ); // } else { // alert("預覽出錯"); // } // }); } } btn.on( 'click' , function() { callback && callback($image.cropper( "getdata" )); return false ; }); return { setsource: function( src ) { // 處理 base64 不支持的情況。 // 一般出現在 ie6-ie8 srcwrap( src, function( src ) { $image.cropper( "setimgsrc" , src); }); container.removeclass( 'webuploader-element-invisible' ); return this ; }, getimagesize: function() { var img = $image.get( 0 ); return { width: img.naturalwidth, height: img.naturalheight } }, setcallback: function( cb ) { callback = cb; return this ; }, disable: function() { $image.cropper( "disable" ); return this ; }, enable: function() { $image.cropper( "enable" ); return this ; } } })(); // ------------------------------ // -----------logic-------------- // ------------------------------ var container = $( '.uploader-container' ); uploader.init(function( src ) { croper.setsource( src ); // 隱藏選擇按鈕。 container.addclass( 'webuploader-element-invisible' ); // 當用戶選擇上傳的時候,開始上傳。 croper.setcallback(function( data ) { uploader.crop(data); uploader.upload(); }); }); // ----------------------------------------------------- // ------------ end ------------------------------------ // ----------------------------------------------------- }); |
還有頁面的部分代碼:
下面是controller部分的代碼:
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
|
@requestmapping (value= "/student/studentimgfileupload" , method=requestmethod.post) @responsebody string studentimgfileupload( @requestparam multipartfile file, httpservletrequest request){ logger.info( "學生頭像上傳...." ) //獲取文件名 string originalfilename = file.getoriginalfilename() logger.info( "上傳文件名:" + originalfilename) string realpath = request.getservletcontext().getrealpath( "/public/student/" ) string uploadfilename = system.currenttimemillis()+ "_" + originalfilename logger.info( "獲取上傳路徑:" + realpath + ", 上傳的真實文件名:" + uploadfilename) boolean flag = true //合并文件 randomaccessfile rafile = null bufferedinputstream inputstream = null try { file dirfile = new file(realpath, uploadfilename) //以讀寫的方式打開目標文件 rafile = new randomaccessfile(dirfile, "rw" ) rafile.seek(rafile.length()) inputstream = new bufferedinputstream(file.getinputstream()) byte [] buf = new byte [ 1024 ] int length = 0 while ((length = inputstream.read(buf)) != - 1 ) { rafile.write(buf, 0 , length) } } catch (exception e){ flag = false logger.info( "上傳出錯:" + e.getmessage()) throw new ioexception(e.getmessage()) } finally { try { if (inputstream != null ) { inputstream.close() } if (rafile != null ) { rafile.close() } } catch (exception e){ flag = false logger.info( "上傳出錯:" + e.getmessage()) throw new ioexception(e.getmessage()) } } } |
這樣就簡單實現了在spring boot項目中使用webuploader進行文件上傳的功能。
總結
以上所述是小編給大家介紹的spring boot 利用webuploader進行文件上傳功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://blog.csdn.net/cckevincyh/article/details/79646321