1、導入資源
2、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
|
<div class = "page-container" > <div class = "row cl" > <label class = "form-label col-xs-4 col-sm-2" ><span class = "c-red" >*</span>項目名稱:</label> <div class = "formcontrols col-xs-8 col-sm-9" > <input type= "text" class = "input-text" value= "${proname }" placeholder= "" id= "" name= "proname" readonly= "readonly" > </div> </div> <div class = "row cl" > <label class = "form-label col-xs-4 col-sm-2" >縮略圖:</label> <div class = "formcontrols col-xs-8 col-sm-9" > <div class = "uploader-thum-container" > <div id= "filelist" class = "uploader-list" ></div> <button id= "btn-star" </div> </div> </div> <div class = "row cl" > <label class = "form-label col-xs-4 col-sm-2" ><span class = "c-red" >*</span>項目發票上傳:</label> <div class = "formcontrols col-xs-8 col-sm-9" > <div class = "uploader-list-container" > <div class = "queuelist" > <div id= "dndarea" class = "placeholder" > <div id= "filepicker-2" ></div> <p>或將照片拖到這里,單次最多可選 300 張</p> </div> </div> <div class = "statusbar" style= "display:none;" > <div class = "progress" > <span class = "text" > 0 %</span> <span class = "percentage" ></span> </div> <div class = "info" ></div> <div class = "btns" > <div id= "filepicker2" ></div> <div class = "uploadbtn" >開始上傳</div> </div> </div> </div> </div> </div> <div class = "row cl" > <div class = "col-xs-8 col-sm-9 col-xs-offset-4 col-sm-offset-2" > <button onclick= "article_add('','invoicevo/save?&projectid=${projectid}&invoicescan=','10001');" class = "btn btn-primary radius" type= "button" > <i class = "hui-iconfont" ></i> 保存 </button> </div> </div> </div> |
3、js代碼
- <script type="text/javascript">
- var imagepath=null;
- function article_save() {
- alert("刷新父級的時候會自動關閉彈層。");
- window.parent.location.reload();
- }
- /*項目發票-添加*/
- function article_add(title, url, w, h) {
- if(imagepath){
- var index = layer.open({
- type : 2,
- title : title,
- content : url+imagepath
- });
- layer.full(index);
- }else{alert("沒有上傳圖片,請先上傳圖片");}
- }
- $(function() {
- $('.skin-minimal input').icheck({
- checkboxclass : 'icheckbox-blue',
- radioclass : 'iradio-blue',
- increasearea : '20%'
- });
- $list = $("#filelist"), $btn = $("#btn-star"), state = "pending",
- uploader;
- var uploader = webuploader.create({
- auto : true,
- swf : 'lib/webuploader/0.1.5/uploader.swf',// swf文件路徑
- // 文件接收服務端。
- server : 'lib/webuploader/0.1.5/server/fileupload.php', // 文件接收服務端。
- // 選擇文件的按鈕。可選。
- // 內部根據當前運行是創建,可能是input元素,也可能是flash.
- pick : '#filepicker',
- // 不壓縮image, 默認如果是jpeg,文件上傳前會壓縮一把再上傳!
- resize : false,
- // 只允許選擇圖片文件。
- accept : {
- title : 'images',
- extensions : 'gif,jpg,jpeg,bmp,png',
- mimetypes : 'image/*'
- }
- });
- // 當有文件被添加進隊列的時候
- uploader
- .on(
- 'filequeued',
- function(file) {
- var $li = $('<div id="' + file.id + '" class="item">'
- + '<div class="pic-box"><img></div>'
- + '<div class="info">'
- + file.name
- + '</div>'
- + '<p class="state">等待上傳...</p>'
- + '</div>'), $img = $li.find('img');
- $list.append($li);
- // 創建縮略圖
- // 如果為非圖片文件,可以不用調用此方法。
- // thumbnailwidth x thumbnailheight 為 100 x 100
- uploader.makethumb(file, function(error, src) {
- if (error) {
- $img.replacewith('<span>不能預覽</span>');
- return;
- }
- $img.attr('src', src);
- }, thumbnailwidth, thumbnailheight);
- });
- // 文件上傳過程中創建進度條實時顯示。
- uploader
- .on(
- 'uploadprogress',
- function(file, percentage) {
- var $li = $('#' + file.id), $percent = $li
- .find('.progress-box .sr-only');
- // 避免重復創建
- if (!$percent.length) {
- $percent = $(
- '<div class="progress-box"><span class="progress-bar radius"><span class="sr-only" style="width:0%"></span></span></div>')
- .appendto($li).find('.sr-only');
- }
- $li.find(".state").text("上傳中");
- $percent.css('width', percentage * 100 + '%');
- });
- // 文件上傳成功,給item添加成功class, 用樣式標記上傳成功。
- uploader.on('uploadsuccess', function(file) {
- $('#' + file.id).addclass('upload-state-success')
- .find(".state").text("已上傳");
- });
- // 文件上傳失敗,顯示上傳出錯。
- uploader.on('uploaderror', function(file) {
- $('#' + file.id).addclass('upload-state-error').find(".state")
- .text("上傳出錯");
- });
- // 完成上傳完了,成功或者失敗,先刪除進度條。
- uploader.on('uploadcomplete', function(file) {
- $('#' + file.id).find('.progress-box').fadeout();
- });
- uploader.on('all', function(type) {
- if (type === 'startupload') {
- state = 'uploading';
- } else if (type === 'stopupload') {
- state = 'paused';
- } else if (type === 'uploadfinished') {
- state = 'done';
- }
- if (state === 'uploading') {
- $btn.text('暫停上傳');
- } else {
- $btn.text('開始上傳');
- }
- });
- $btn.on('click', function() {
- if (state === 'uploading') {
- uploader.stop();
- } else {
- uploader.upload();
- }
- });
- });
- (function($) {
- // 當domready的時候開始初始化
- $(function() {
- var $wrap = $('.uploader-list-container'),
- // 圖片容器
- $queue = $('<ul class="filelist"></ul>').appendto(
- $wrap.find('.queuelist')),
- // 狀態欄,包括進度和控制按鈕
- $statusbar = $wrap.find('.statusbar'),
- // 文件總體選擇信息。
- $info = $statusbar.find('.info'),
- // 上傳按鈕
- $upload = $wrap.find('.uploadbtn'),
- // 沒選擇文件之前的內容。
- $placeholder = $wrap.find('.placeholder'),
- $progress = $statusbar.find('.progress').hide(),
- // 添加的文件數量
- filecount = 0,
- // 添加的文件總大小
- filesize = 0,
- // 優化retina, 在retina下這個值是2
- ratio = window.devicepixelratio || 1,
- // 縮略圖大小
- thumbnailwidth = 110 * ratio, thumbnailheight = 110 * ratio,
- // 可能有pedding, ready, uploading, confirm, done.
- state = 'pedding',
- // 所有文件的進度信息,key為file id
- percentages = {},
- // 判斷瀏覽器是否支持圖片的base64
- issupportbase64 = (function() {
- var data = new image();
- var support = true;
- data.onload = data.onerror = function() {
- if (this.width != 1 || this.height != 1) {
- support = false;
- }
- }
- data.src = "data:image/gif;base64,r0lgodlhaqabaiaaaaaaap///ywaaaaaaqabaaacauwaow==";
- return support;
- })(),
- // 檢測是否已經安裝flash,檢測flash的版本
- flashversion = (function() {
- var version;
- try {
- version = navigator.plugins['shockwave flash'];
- version = version.description;
- } catch (ex) {
- try {
- version = new activexobject(
- 'shockwaveflash.shockwaveflash')
- .getvariable('$version');
- } catch (ex2) {
- version = '0.0';
- }
- }
- version = version.match(/d+/g);
- return parsefloat(version[0] + '.' + version[1], 10);
- })(),
- supporttransition = (function() {
- var s = document.createelement('p').style, r = 'transition' in s
- || 'webkittransition' in s
- || 'moztransition' in s
- || 'mstransition' in s || 'otransition' in s;
- s = null;
- return r;
- })(),
- // webuploader實例
- uploader;
- if (!webuploader.uploader.support('flash')
- && webuploader.browser.ie) {
- // flash 安裝了但是版本過低。
- if (flashversion) {
- (function(container) {
- window['expressinstallcallback'] = function(state) {
- switch (state) {
- case 'download.cancelled':
- alert('您取消了更新!')
- break;
- case 'download.failed':
- alert('安裝失敗')
- break;
- default:
- alert('安裝已成功,請刷新!');
- break;
- }
- delete window['expressinstallcallback'];
- };
- var swf = 'expressinstall.swf';
- // insert flash object
- var html = '<object type="application/'
- + 'x-shockwave-flash" data="' + swf + '" ';
- if (webuploader.browser.ie) {
- html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
- }
- html += 'width="100%" height="100%" style="outline:0">'
- + '<param name="movie" value="' + swf + '" />'
- + '<param name="wmode" value="transparent" />'
- + '<param name="allowscriptaccess" value="always" />'
- + '</object>';
- container.html(html);
- })($wrap);
- // 壓根就沒有安轉。
- } else {
- $wrap
- .html('<a href="http://www.adobe.com/go/getflashplayer" target="_blank" border="0"><img alt="get flash player" src="http://www.adobe.com/macromedia/style_guide/images/160x41_get_flash_player.jpg" /></a>');
- }
- return;
- } else if (!webuploader.uploader.support()) {
- alert('web uploader 不支持您的瀏覽器!');
- return;
- }
- // 實例化
- uploader = webuploader.create({
- pick : {
- id : '#filepicker-2',
- label : '點擊選擇圖片'
- },
- formdata : {
- uid : 123
- },
- dnd : '#dndarea',
- paste : '#uploader',
- swf : 'lib/webuploader/0.1.5/uploader.swf',
- chunked : false,
- chunksize : 512 * 1024,
- server : 'invoicevo/news_uploder?&projectid=${projectid}',
- // runtimeorder: 'flash',
- // accept: {
- // title: 'images',
- // extensions: 'gif,jpg,jpeg,bmp,png',
- // mimetypes: 'image/*'
- // },
- // 禁掉全局的拖拽功能。這樣不會出現圖片拖進頁面的時候,把圖片打開。
- disableglobaldnd : true,
- filenumlimit : 300,
- filesizelimit : 200 * 1024 * 1024, // 200 m
- filesinglesizelimit : 50 * 1024 * 1024
- // 50 m
- });
- // 拖拽時不接受 js, txt 文件。
- uploader.on('dndaccept', function(items) {
- var denied = false, len = items.length, i = 0,
- // 修改js類型
- unallowed = 'text/plain;application/javascript ';
- for (; i < len; i++) {
- // 如果在列表里面
- if (~unallowed.indexof(items[i].type)) {
- denied = true;
- break;
- }
- }
- return !denied;
- });
- uploader.on('dialogopen', function() {
- console.log('here');
- });
- // uploader.on('filesqueued', function() {
- // uploader.sort(function( a, b ) {
- // if ( a.name < b.name )
- // return -1;
- // if ( a.name > b.name )
- // return 1;
- // return 0;
- // });
- // });
- // 添加“添加文件”的按鈕,
- /* uploader.addbutton({
- id : '#filepicker2',
- label : '繼續添加'
- }); */
- uploader.on('ready', function() {
- window.uploader = uploader;
- });
- // 當有文件添加進來時執行,負責view的創建
- function addfile(file) {
- var $li = $('<li id="' + file.id + '">'
- + '<p class="title">' + file.name + '</p>'
- + '<p class="imgwrap"></p>'
- + '<p class="progress"><span></span></p>' + '</li>'),
- $btns = $(
- '<div class="file-panel">'
- + '<span class="cancel">刪除</span>'
- + '<span class="rotateright">向右旋轉</span>'
- + '<span class="rotateleft">向左旋轉</span></div>')
- .appendto($li), $prgress = $li
- .find('p.progress span'), $wrap = $li
- .find('p.imgwrap'), $info = $('<p class="error"></p>'),
- showerror = function(code) {
- switch (code) {
- case 'exceed_size':
- text = '文件大小超出';
- break;
- case 'interrupt':
- text = '上傳暫停';
- break;
- default:
- text = '上傳失敗,請重試';
- break;
- }
- $info.text(text).appendto($li);
- };
- if (file.getstatus() === 'invalid') {
- showerror(file.statustext);
- } else {
- // @todo lazyload
- $wrap.text('預覽中');
- uploader
- .makethumb(
- file,
- function(error, src) {
- var img;
- if (error) {
- $wrap.text('不能預覽');
- return;
- }
- if (issupportbase64) {
- img = $('<img src="'+src+'">');
- $wrap.empty().append(img);
- } else {
- $
- .ajax(
- 'lib/webuploader/0.1.5/server/preview.php',
- {
- method : 'post',
- data : src,
- datatype : 'json'
- })
- .done(
- function(
- response) {
- if (response.result) {
- img = $('<img src="'+response.result+'">');
- $wrap
- .empty()
- .append(
- img);
- } else {
- $wrap
- .text("預覽出錯");
- }
- });
- }
- }, thumbnailwidth, thumbnailheight);
- percentages[file.id] = [ file.size, 0 ];
- file.rotation = 0;
- }
- file.on('statuschange', function(cur, prev) {
- if (prev === 'progress') {
- $prgress.hide().width(0);
- } else if (prev === 'queued') {
- $li.off('mouseenter mouseleave');
- $btns.remove();
- }
- // 成功
- if (cur === 'error' || cur === 'invalid') {
- console.log(file.statustext);
- showerror(file.statustext);
- percentages[file.id][1] = 1;
- } else if (cur === 'interrupt') {
- showerror('interrupt');
- } else if (cur === 'queued') {
- percentages[file.id][1] = 0;
- } else if (cur === 'progress') {
- $info.remove();
- $prgress.css('display', 'block');
- } else if (cur === 'complete') {
- $li.append('<span class="success"></span>');
- }
- $li.removeclass('state-' + prev).addclass(
- 'state-' + cur);
- });
- $li.on('mouseenter', function() {
- $btns.stop().animate({
- height : 30
- });
- });
- $li.on('mouseleave', function() {
- $btns.stop().animate({
- height : 0
- });
- });
- $btns
- .on(
- 'click',
- 'span',
- function() {
- var index = $(this).index(), deg;
- switch (index) {
- case 0:
- uploader.removefile(file);
- return;
- case 1:
- file.rotation += 90;
- break;
- case 2:
- file.rotation -= 90;
- break;
- }
- if (supporttransition) {
- deg = 'rotate(' + file.rotation
- + 'deg)';
- $wrap.css({
- '-webkit-transform' : deg,
- '-mos-transform' : deg,
- '-o-transform' : deg,
- 'transform' : deg
- });
- } else {
- $wrap
- .css(
- 'filter',
- 'progid:dximagetransform.microsoft.basicimage(rotation='
- + (~~((file.rotation / 90) % 4 + 4) % 4)
- + ')');
- }
- });
- $li.appendto($queue);
- }
- // 負責view的銷毀
- function removefile(file) {
- var $li = $('#' + file.id);
- delete percentages[file.id];
- updatetotalprogress();
- $li.off().find('.file-panel').off().end().remove();
- }
- function updatetotalprogress() {
- var loaded = 0, total = 0, spans = $progress.children(), percent;
- $.each(percentages, function(k, v) {
- total += v[0];
- loaded += v[0] * v[1];
- });
- percent = total ? loaded / total : 0;
- spans.eq(0).text(math.round(percent * 100) + '%');
- spans.eq(1).css('width', math.round(percent * 100) + '%');
- updatestatus();
- }
- function updatestatus() {
- var text = '', stats;
- if (state === 'ready') {
- text = '選中' + filecount + '張圖片,共'
- + webuploader.formatsize(filesize) + '。';
- } else if (state === 'confirm') {
- stats = uploader.getstats();
- if (stats.uploadfailnum) {
- text = '已成功上傳'
- + stats.successnum
- + '張照片至xx相冊,'
- + stats.uploadfailnum
- + '張照片上傳失敗,<a class="retry" href="#" rel="external nofollow" rel="external nofollow" >重新上傳</a>失敗圖片或<a class="ignore" href="#" rel="external nofollow" rel="external nofollow" >忽略</a>'
- }
- } else {
- stats = uploader.getstats();
- text = '共' + filecount + '張('
- + webuploader.formatsize(filesize) + '),已上傳'
- + stats.successnum + '張';
- if (stats.uploadfailnum) {
- text += ',失敗' + stats.uploadfailnum + '張';
- }
- }
- $info.html(text);
- }
- function setstate(val) {
- var file, stats;
- if (val === state) {
- return;
- }
- $upload.removeclass('state-' + state);
- $upload.addclass('state-' + val);
- state = val;
- switch (state) {
- case 'pedding':
- $placeholder.removeclass('element-invisible');
- $queue.hide();
- $statusbar.addclass('element-invisible');
- uploader.refresh();
- break;
- case 'ready':
- $placeholder.addclass('element-invisible');
- $('#filepicker2').removeclass('element-invisible');
- $queue.show();
- $statusbar.removeclass('element-invisible');
- uploader.refresh();
- break;
- case 'uploading':
- $('#filepicker2').addclass('element-invisible');
- $progress.show();
- $upload.text('暫停上傳');
- break;
- case 'paused':
- $progress.show();
- $upload.text('繼續上傳');
- break;
- case 'confirm':
- $progress.hide();
- $('#filepicker2').removeclass('element-invisible');
- $upload.text('開始上傳');
- stats = uploader.getstats();
- if (stats.successnum && !stats.uploadfailnum) {
- setstate('finish');
- return;
- }
- break;
- case 'finish':
- stats = uploader.getstats();
- if (stats.successnum) {
- alert('上傳成功');
- } else {
- // 沒有成功的圖片,重設
- state = 'done';
- location.reload();
- }
- break;
- }
- updatestatus();
- }
- uploader.onuploadprogress = function(file, percentage) {
- var $li = $('#' + file.id), $percent = $li
- .find('.progress span');
- $percent.css('width', percentage * 100 + '%');
- percentages[file.id][1] = percentage;
- updatetotalprogress();
- };
- uploader.onfilequeued = function(file) {
- filecount++;
- filesize += file.size;
- if (filecount === 1) {
- $placeholder.addclass('element-invisible');
- $statusbar.show();
- }
- addfile(file);
- setstate('ready');
- updatetotalprogress();
- };
- uploader.onfiledequeued = function(file) {
- filecount--;
- filesize -= file.size;
- if (!filecount) {
- setstate('pedding');
- }
- removefile(file);
- updatetotalprogress();
- };
- /*獲取服務器返回的數據*/
- uploader.on('uploadsuccess', function(file, response) {
- alert(response.status);
- if (response.status == "success") {
- imagepath =response.filepath;
- alert("文件保存路徑:" + response.filepath);
- } else if (response.status == "error")
- alert(response.error);
- });
- uploader.on('all', function(type) {
- var stats;
- //alert(type);
- switch (type) {
- case 'uploadfinished':
- setstate('confirm');
- break;
- case 'startupload':
- setstate('uploading');
- break;
- case 'stopupload':
- setstate('paused');
- break;
- }
- });
- uploader.onerror = function(code) {
- alert('eroor: ' + code);
- };
- $upload.on('click', function() {
- if ($(this).hasclass('disabled')) {
- return false;
- }
- if (state === 'ready') { //點擊上傳按鈕,進入準備狀態。
- uploader.upload(); //開始上傳
- } else if (state === 'paused') {
- uploader.upload();
- } else if (state === 'uploading') {
- uploader.stop();
- }
- });
- $info.on('click', '.retry', function() {
- uploader.retry();
- });
- $info.on('click', '.ignore', function() {
- alert('todo');
- });
- $upload.addclass('state-' + state);
- updatetotalprogress();
- });
- })(jquery);
- </script>
注意:
4、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
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
|
/** * 跳轉到上傳發票的頁面 * @param proname * @param map * @return */ @requestmapping (value = "/upload" ) public string invoiceupload(string proname, long id,map<string, object> map){ map.put( "proname" , proname); projectservice.getproject(id); map.put( "projectid" , id); return "project/invoiceupload" ; } /** * 上傳發票并保存導數據庫 * @param file * @param request * @param response * @return */ @responsebody @requestmapping (value = "/news_uploder" , method ={requestmethod.post,requestmethod.get}, produces = "application/json; charset=utf-8" ) public jsonobject uploder( @requestparam multipartfile[] file, long projectid,httpservletrequest request,httpservletresponse response){ string flag= null ; jsonobject jsonobject = new jsonobject(); try { webuploaderutil webuploaderutil= new webuploaderutil(); webuploaderutil.upload(file[ 0 ], "upload/invoice/" , request); flag=webuploaderutil.getfilename(); jsonobject.put( "filepath" , flag); jsonobject.put( "status" , "success" ); } catch (exception e) { e.printstacktrace(); } return jsonobject; } 5 、工具類 package com.softjx.util; /** *project name: qdlimap *file name: webuploaderutil.java *package name: com.ltmap.platform.cms.util *date: 2017年4月13日 下午6:30:45 *copyright (c) 2017,[email protected] all rights reserved. */ import java.io.file; import java.text.simpledateformat; import java.util.date; import javax.servlet.http.httpservletrequest; import org.springframework.web.multipart.multipartfile; /** *title: webuploaderutil<br/> *description: *@company: 勵圖高科<br/> *@author: 劉云生 *@version: v1.0 *@since: jdk 1.8.0_40 *@date: 2017年4月13日 下午6:30:45 <br/> */ public class webuploaderutil { private string allowsuffix = "jpg,png,gif,jpeg" ; //允許文件格式 private long allowsize = 2l; //允許文件大小 private string filename; private string[] filenames; public string getallowsuffix() { return allowsuffix; } public void setallowsuffix(string allowsuffix) { this .allowsuffix = allowsuffix; } public long getallowsize() { return allowsize* 1024 * 1024 ; } public void setallowsize( long allowsize) { this .allowsize = allowsize; } public string getfilename() { return filename; } public void setfilename(string filename) { this .filename = filename; } public string[] getfilenames() { return filenames; } public void setfilenames(string[] filenames) { this .filenames = filenames; } /** * * @title: getfilenamenew * @description: todo * @param: @return * @return: string * @author: 劉云生 * @date: 2017年4月14日 上午10:17:35 * @throws */ private string getfilenamenew(){ simpledateformat fmt = new simpledateformat( "yyyymmddhhmmsssss" ); return fmt.format( new date()); } /** * * @title: uploads * @description: todo * @param: @param files * @param: @param destdir * @param: @param request * @param: @throws exception * @return: void * @author: 劉云生 * @date: 2017年4月14日 上午10:17:14 * @throws */ public void uploads(multipartfile[] files, string destdir,httpservletrequest request) throws exception { string path = request.getcontextpath(); string basepath = request.getscheme()+ "://" +request.getservername()+ ":" +request.getserverport()+path; try { filenames = new string[files.length]; int index = 0 ; for (multipartfile file : files) { string suffix = file.getoriginalfilename().substring(file.getoriginalfilename().lastindexof( "." )+ 1 ); int length = getallowsuffix().indexof(suffix); if (length == - 1 ){ throw new exception( "請上傳允許格式的文件" ); } if (file.getsize() > getallowsize()){ throw new exception( "您上傳的文件大小已經超出范圍" ); } string realpath = request.getsession().getservletcontext().getrealpath( "/" ); file destfile = new file(realpath+destdir); if (!destfile.exists()){ destfile.mkdirs(); } string filenamenew = getfilenamenew()+ "." +suffix; // file f = new file(destfile.getabsolutefile()+ "\" +filenamenew); file.transferto(f); f.createnewfile(); filenames[index++] =basepath+destdir+filenamenew; } } catch (exception e) { throw e; } } /** * * @title: upload * @description: todo * @param: @param file * @param: @param destdir * @param: @param request * @param: @throws exception * @return: void * @author: 劉云生 * @date: 2017年4月14日 上午10:16:16 * @throws */ public void upload(multipartfile file, string destdir,httpservletrequest request) throws exception { string path = request.getcontextpath(); //http://localhost:8088/huahang string basepath = request.getscheme()+ "://" +request.getservername()+ ":" +request.getserverport()+path; try { string suffix = file.getoriginalfilename().substring(file.getoriginalfilename().lastindexof( "." )+ 1 ); int length = getallowsuffix().indexof(suffix); if (length == - 1 ){ throw new exception( "請上傳允許格式的文件" ); } if (file.getsize() > getallowsize()){ throw new exception( "您上傳的文件大小已經超出范圍" ); } string realpath = request.getsession().getservletcontext().getrealpath( "/" )+ "/" ; file destfile = new file(realpath+destdir); if (!destfile.exists()){ destfile.mkdirs(); } string filenamenew = getfilenamenew()+ "." +suffix; file f = new file(destfile.getabsolutefile()+ "/" +filenamenew); file.transferto(f); f.createnewfile(); //包含網站的全路徑http://localhost:8080/qdlimap/upload/user/20170414104142667.png //filename = basepath+destdir+filenamenew; //返回相對路徑upload/user/20170414104142667.png filename = destdir+filenamenew; } catch (exception e) { throw e; } } } |
總結
以上所述是小編給大家介紹的webuploader 實現圖片批量上傳功能附實例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://www.cnblogs.com/HawkFalcon/archive/2017/11/30/7727028.html