百度WebUploader上傳圖片,圖片回顯編輯,查看
阿新 • • 發佈:2017-09-06
set 唯一性 original 無需 同名 sch nag fin enum
頁面前端使用的是bootstrap,java後端springMVC , 上傳用的WebUploader,先說說上傳圖片,回顯編輯圖片在下一篇
如果僅僅只需要上傳圖片,不需要回顯進行編輯圖片,使用WebUploader官網的例子即可實現,如果要圖片回顯進行編輯,則需要做一些修改,我是將上傳圖片和回顯編輯圖片分開寫的。我這裏的上傳,回顯編輯圖片,可以當做公共方法,傳相應的參數即可。
(我這裏是點擊保存的時候才開始上傳圖片,因為我還要保存其他數據,所以我是先保存的其他數據,然後上傳的圖片,提示:WebUploader是一張一張圖片上傳的,它每上傳一張圖片,都會去調用一次java後臺方法)
1. 先引入js和css
2.在jsp頁面
<div id="uploader" class="commonWebUploader"> //此處calss引入的是上傳的js <div class="queueList"> <div id="dndArea" class="placeholder"> <div id="filePicker"></div> <p>或將照片拖到這裏,單次最多可選10張</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" class="addFileBtn"></div> <!-- <div class="uploadBtn">開始上傳</div> --> </div> </div> </div>
3.自定義的上傳commonWebUploader.js
// 使用命名空間。 (function(window) { // 如果需要在模態框中使用webuploader,那麽必須先調用prepareModal, // 再調用initWebUploader。這樣可以解決模態框中使用webuploader出現的BUG。 // 例如prepareModal(‘#addProductModal‘) this.prepareModal = function(modalId) { var _$modal = $(modalId); _$modal.css(‘display‘, ‘block‘); _$modal.addClass("webuploader-element-invisible"); _$modal.on(‘show.bs.modal‘, function() { _$modal.removeClass("webuploader-element-invisible"); }); } // 返回一個webuploader實例。 // 例如initWebUploader(‘#uploader‘, ‘#filePicker‘, ‘#filePicker2‘, ‘uploadMethod‘) this.initWebUploader = function(webUploaderId, filePickerId, fileAddId, uploadUrl) { //前三個參數對應的是jsp頁面的div的id,最後一個參數,是後臺調用的上傳方法名字 var $ = jQuery, // just in case. Make sure it‘s not an other library. $wrap = $(webUploaderId), // 圖片容器 $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, thumbnailWidth = ratio, thumbnailHeight = ratio, // 可能有pedding, ready, uploading, confirm, done. state = ‘pedding‘, // 所有文件的進度信息,key為file id percentages = {}, // WebUploader實例 wuploader; if (!WebUploader.Uploader.support()) { //alert(‘Web Uploader 不支持您的瀏覽器!如果你使用的是IE瀏覽器,請嘗試升級 flash 播放器‘); layer.msg(‘Web Uploader 不支持您的瀏覽器!如果你使用的是IE瀏覽器,請嘗試升級 flash 播放器‘, { icon: 2 }); throw new Error(‘WebUploader does not support the browser you are using.‘); } // 實例化 wuploader = WebUploader.create({ pick : { id : filePickerId, label : ‘點擊選擇圖片‘ }, dnd : webUploaderId + ‘ .queueList‘, paste : window.document.body, accept : { title : ‘Images‘, extensions : ‘gif,jpg,jpeg,bmp,png‘, mimeTypes : ‘image/gif,image/jpg,image/jpeg,image/bmp,image/png‘ }, // swf文件路徑 swf : ‘/js/plugins/webuploader/Uploader.swf‘, disableGlobalDnd : true, chunked : true, server : uploadUrl, fileNumLimit : 10 //fileSizeLimit: 5 * 1024 * 1024, // 5 M //fileSingleSizeLimit: 1 * 1024 * 1024 // 1 M }); // 添加“添加文件”的按鈕, wuploader.addButton({ id : fileAddId, label : ‘繼續添加‘ }); // 當有文件添加進來時執行,負責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></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(‘預覽中‘); wuploader.makeThumb(file, function(error, src) { if (error) { $wrap.text(‘不能預覽‘); return; } //var img = $(‘<img src="‘+src+‘">‘); // 使用data-fancybox-href,解決IE中圖片顯示的問題。 // TODO data-fancybox-group怎麽確保唯一性? var img = $(‘<a class="fancybox" data-fancybox-group="gallery‘ + webUploaderId + ‘" data-fancybox-href="‘ + src + ‘"><img src="‘ + src + ‘"></a>‘); $wrap.empty().append(img); }, thumbnailWidth, thumbnailHeight); percentages[file.id] = [ file.size, 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: wuploader.removeFile(file); return; } }); $li.appendTo($queue); } // 負責view的銷毀 function doRemoveFile(file) { delete percentages[file.id]; // 不處理“進度”的更新。讓調用方自己負責更新。 by tanzx 2017-08-01 //updateTotalProgress(); var $li = $(‘#‘ + file.id); // 當文件顯示出來時,才做移除。 if ($li) { $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 = wuploader.getStats(); if (stats.uploadFailNum) { text = ‘已成功上傳‘ + stats.successNum + ‘張照片至XX相冊,‘ + stats.uploadFailNum + ‘張照片上傳失敗,<a class="retry" href="#">重新上傳</a>失敗圖片或<a class="ignore" href="#">忽略</a>‘ } } else { stats = wuploader.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 && $upload.removeClass(‘state-‘ + state); $upload && $upload.addClass(‘state-‘ + val); state = val; switch (state) { case ‘pedding‘: $placeHolder.removeClass(‘element-invisible‘); $queue.parent().removeClass(‘filled‘); $queue.hide(); $statusBar.addClass(‘element-invisible‘); wuploader.refresh(); break; case ‘ready‘: $placeHolder.addClass(‘element-invisible‘); $(fileAddId).removeClass(‘element-invisible‘); // 修改上傳按鈕為可用。 by tanzx 2017-08-01 $upload && $upload.removeClass(‘disabled‘); $queue.parent().addClass(‘filled‘); $queue.show(); $statusBar.removeClass(‘element-invisible‘); wuploader.refresh(); break; case ‘uploading‘: $(fileAddId).addClass(‘element-invisible‘); $progress.show(); $upload && $upload.text(‘暫停上傳‘); break; case ‘paused‘: $progress.show(); $upload && $upload.text(‘繼續上傳‘); break; case ‘confirm‘: $progress.hide(); $upload && $upload.text(‘開始上傳‘).addClass(‘disabled‘); stats = wuploader.getStats(); if (stats.successNum && !stats.uploadFailNum) { setState(‘finish‘); return; } break; case ‘finish‘: stats = wuploader.getStats(); if (stats.successNum) { //alert(‘上傳成功‘); layer.msg(‘上傳成功‘, { icon: 1, offset: ‘t‘ }); } else { // 沒有成功的圖片,重設 state = ‘done‘; location.reload(); } break; } updateStatus(); } wuploader.onUploadProgress = function(file, percentage) { var $li = $(‘#‘ + file.id), $percent = $li.find(‘.progress span‘); $percent.css(‘width‘, percentage * 100 + ‘%‘); percentages[file.id][1] = percentage; updateTotalProgress(); }; wuploader.onFileQueued = function(file) { fileCount++; fileSize += file.size; if (fileCount === 1) { $placeHolder.addClass(‘element-invisible‘); $statusBar.show(); } addFile(file); // 不需要每次添加文件,都調用setState(‘ready‘)。by tanzx 2017-08-01 setState(‘ready‘); updateTotalProgress(); }; wuploader.onFileDequeued = function(file) { fileCount--; fileSize -= file.size; if (!fileCount) { setState(‘pedding‘); } doRemoveFile(file); updateTotalProgress(); }; // 添加Reset監聽。by tanzx 2017-08-01 // TODO reset不知道有沒有問題。是否選擇用destroy? wuploader.onReset = function() { fileCount = 0; fileSize = 0; setState(‘pedding‘); // 移除頁面上的圖片。 $.each(wuploader.getFiles(), function(index, value) { doRemoveFile(value); }); updateTotalProgress(); }; wuploader.on(‘all‘, function(type) { var stats; switch (type) { case ‘uploadFinished‘: setState(‘confirm‘); break; case ‘startUpload‘: setState(‘uploading‘); break; case ‘stopUpload‘: setState(‘paused‘); break; } }); wuploader.onError = function(code) { //alert(‘Error: ‘ + code); var text = ‘‘; if (code == ‘F_DUPLICATE‘) { text = ‘文件重復!‘; } else { text = ‘Error: ‘ + code; } layer.msg(text, { icon: 2, offset: ‘t‘ }); }; $upload && $upload.on(‘click‘, function() { if ($(this).hasClass(‘disabled‘)) { return false; } if (state === ‘ready‘) { wuploader.upload(); } else if (state === ‘paused‘) { wuploader.upload(); } else if (state === ‘uploading‘) { wuploader.stop(); } }); $info.on(‘click‘, ‘.retry‘, function() { wuploader.retry(); }); $info.on(‘click‘, ‘.ignore‘, function() { //alert(‘todo‘); //layer.msg(‘todo‘, { icon: 3, offset: ‘t‘ }); //執行忽略動作,重置 wuploader.reset(); }); $upload && $upload.addClass(‘state-‘ + state); updateTotalProgress(); // WebUploader實例 return wuploader; } // end initWebUploader window.CommonWebUploader = this; })(window);commonWebUploader.js
4.如果上傳按鈕是在頁面中,使用如下方法調用
//初始化上傳插件 function initWebUploaderUI(){ // WebUploader實例,前三個參數對應的是jsp頁面的div的id,最後一個參數,是後臺調用的上傳方法名字 wuploader = CommonWebUploader.initWebUploader(‘#uploader‘, ‘#filePicker‘, ‘#filePicker2‘, ‘uploadFile‘); // 所有文件上傳結束時 wuploader.on( ‘uploadFinished‘, function() { var stats = wuploader.getStats(); // 全部上傳成功 if (!stats.uploadFailNum) { alert("上傳成功!"); } }); }
5.在點擊保存時,調用保存方法(我是先保存的其他數據,再上傳的圖片)
function save(){ $.ajax({ cache: true, type: "POST", contentType: "application/json;charset=UTF-8", url:"", data:JSON.stringify(params), async: true, error: function(request) { alert("修改失敗"); }, success: function(){ wuploader.options.formData.ownerID = moduleID; //傳你需要的參數,如果僅僅是上傳,不要做其他操作,則無需傳參數 wuploader.options.formData.fileType = 2; wuploader.upload(); // 上傳文件 } }); }保存方法
6.java後臺的上傳方法(可根據自己的需要進行適當的修改)
//上傳模塊圖片 @RequestMapping(path="/uploadFile", method=RequestMethod.POST) public @ResponseBody boolean upload(@RequestParam("file") MultipartFile file,int ownerID,int fileType)throws Exception{ //文件上傳到服務器 return moduleManageService.uploadModuleOrFunctionFile(file,ownerID,fileType); }
//上傳圖片到服務器 public boolean uploadModuleOrFunctionFile(MultipartFile file, int ownerID, int fileType) { boolean result = false; try { Path path; if(fileType==ProductModuleFunctionFile.TYPE_MODULE){ path = Paths.get(uploadPathProperties.getModuleFile(), Integer.toString(ownerID)); }else{ path = Paths.get(uploadPathProperties.getFunctionFile(), Integer.toString(ownerID)); } // 獲取上傳文件的文件名 // 用UUID替換掉文件名。 // 避免:上傳多個文件時,瀏覽器中選擇了客戶機上不同目錄下的同名文件,此時出現文件覆蓋問題。 String fileExtension = FilenameUtils.getExtension(file.getOriginalFilename()); fileExtension = StringUtils.isNotBlank(fileExtension) ? FilenameUtils.EXTENSION_SEPARATOR_STR + fileExtension : ""; String fileName = UUID.randomUUID().toString() + fileExtension; Path fpath = Files.createDirectories(path).resolve(fileName); file.transferTo(fpath.toFile()); // 插入產品對應文件關系。 addProductFile(ownerID, fileName, fileType); } catch (IllegalStateException | IOException e) { logger.error("上傳文件保存失敗!", e); // TODO 拋出上傳失敗異常。 } return result; }service
百度WebUploader上傳圖片,圖片回顯編輯,查看