百度WebUploader上傳圖片,圖片回顯編輯,查看


       編輯圖片,可以刪除上次上傳的圖片,可以新加上傳圖片

1.首選還是引入css和js(兩個css,三個js)

自定義css

.webuploader-container {
    position: relative;
}
.webuploader-element-invisible {
    position: absolute !important;
    clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
    clip: rect(1px,1px,1px,1px);
}
.webuploader-pick {
    position: relative;
    display: inline-block;
    cursor: pointer;
    background: #0E9AEF;
    padding: 10px 15px;
    color: #fff;
    text-align: center;
    border-radius: 3px;
    overflow: hidden;
}
.webuploader-pick-hover {
    background: #00a2d4;
}

.webuploader-pick-disable {
    opacity: 0.6;
    pointer-events:none;
}
webuploader.css
.commonWebUploader .queueList {
    /*margin: 20px;*/
    margin-bottom: 15px;
    border: 3px dashed #e6e6e6;
}
.commonWebUploader .queueList.filled {
    /*padding: 17px;*/
    margin: 0;
    border: 3px dashed transparent;
}
.commonWebUploader .queueList.webuploader-dnd-over {
    border: 3px dashed #999999;
}

.commonWebUploader p {margin: 0;}

.element-invisible {
    position: absolute !important;
    clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
    clip: rect(1px,1px,1px,1px);
}

.commonWebUploader .placeholder {
    min-height: 200px;
    padding-top: 100px;
    text-align: center;
    background: url(../../img/webuploader.png) center 20px no-repeat;
    color: #cccccc;
    font-size: 18px;
    position: relative;
}

.commonWebUploader .placeholder .webuploader-pick {
    font-size: 18px;
    background: #00b7ee;
    border-radius: 3px;
    line-height: 44px;
    padding: 0 30px;
    /*width: 120px;*/
    color: #fff;
    display: inline-block;
    /*margin: 0 auto 20px auto;*/
    cursor: pointer;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
}

.commonWebUploader .placeholder .webuploader-pick-hover {
    background: #00a2d4;
}

.commonWebUploader .placeholder .flashTip {
    color: #666666;
    font-size: 12px;
    position: absolute;
    width: 100%;
    text-align: center;
    bottom: 20px;
}
.commonWebUploader .placeholder .flashTip a {
    color: #0785d1;
    text-decoration: none;
}
.commonWebUploader .placeholder .flashTip a:hover {
    text-decoration: underline;
}

.commonWebUploader .filelist,
.editableGallery .filelist {
    list-style: none;
    margin: 0;
    padding: 0;
}

.commonWebUploader .filelist:after,
.editableGallery .filelist:after {
    content: '';
    display: block;
    width: 0;
    height: 0;
    overflow: hidden;
    clear: both;
}

.commonWebUploader .filelist li,
.editableGallery .filelist li {
    width: 110px;
    height: 110px;
    background: url(../../img/bg.png) no-repeat;
    text-align: center;
    margin: 0 8px 20px 0;
    position: relative;
    display: inline;
    float: left;
    overflow: hidden;
    font-size: 12px;
}

.commonWebUploader .filelist li p.log {
    position: relative;
    top: -45px;
}

.commonWebUploader .filelist li p.title {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow : ellipsis;
    top: 5px;
    text-indent: 5px;
    text-align: left;
}

.commonWebUploader .filelist li p.progress {
    position: absolute;
    width: 100%;
    bottom: 0;
    left: 0;
    height: 8px;
    overflow: hidden;
    z-index: 50;
    margin: 0;
    border-radius: 0;
    background: none;
    -webkit-box-shadow: 0 0 0;
}
.commonWebUploader .filelist li p.progress span {
    display: none;
    overflow: hidden;
    width: 0;
    height: 100%;
    background: #1483d8 url(../../img/progress.png) repeat-x;

    -webit-transition: width 200ms linear;
    -moz-transition: width 200ms linear;
    -o-transition: width 200ms linear;
    -ms-transition: width 200ms linear;
    transition: width 200ms linear;

    -webkit-animation: progressmove 2s linear infinite;
    -moz-animation: progressmove 2s linear infinite;
    -o-animation: progressmove 2s linear infinite;
    -ms-animation: progressmove 2s linear infinite;
    animation: progressmove 2s linear infinite;

    -webkit-transform: translateZ(0);
}

@-webkit-keyframes progressmove {
    0% {
       background-position: 0 0;
    }
    100% {
       background-position: 17px 0;
    }
}
@-moz-keyframes progressmove {
    0% {
       background-position: 0 0;
    }
    100% {
       background-position: 17px 0;
    }
}
@keyframes progressmove {
    0% {
       background-position: 0 0;
    }
    100% {
       background-position: 17px 0;
    }
}

.commonWebUploader .filelist li p.imgWrap,
.editableGallery .filelist li p.imgWrap {
    position: relative;
    z-index: 2;
    line-height: 110px;
    vertical-align: middle;
    overflow: hidden;
    width: 110px;
    height: 110px;

    -webkit-transform-origin: 50% 50%;
    -moz-transform-origin: 50% 50%;
    -o-transform-origin: 50% 50%;
    -ms-transform-origin: 50% 50%;
    transform-origin: 50% 50%;

    -webit-transition: 200ms ease-out;
    -moz-transition: 200ms ease-out;
    -o-transition: 200ms ease-out;
    -ms-transition: 200ms ease-out;
    transition: 200ms ease-out;
}

.commonWebUploader .filelist li img,
.editableGallery .filelist li img {
    width: 100%;
}

.commonWebUploader .filelist li p.error {
    background: #f43838;
    color: #fff;
    position: absolute;
    bottom: 0;
    left: 0;
    height: 28px;
    line-height: 28px;
    width: 100%;
    z-index: 100;
}

.commonWebUploader .filelist li .success {
    display: block;
    position: absolute;
    left: 0;
    bottom: 0;
    height: 40px;
    width: 100%;
    z-index: 200;
    background: url(../../img/success.png) no-repeat right bottom;
}

.commonWebUploader .filelist div.file-panel,
.editableGallery .filelist div.file-panel {
    position: absolute;
    height: 0;
    filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#80000000', endColorstr='#80000000')\0;
    background: rgba( 0, 0, 0, 0.5 );
    width: 100%;
    top: 0;
    left: 0;
    overflow: hidden;
    z-index: 300;
}

.commonWebUploader .filelist div.file-panel span,
.editableGallery .filelist div.file-panel span {
    width: 24px;
    height: 24px;
    display: inline;
    float: right;
    text-indent: -9999px;
    overflow: hidden;
    background: url(../../img/icons.png) no-repeat;
    margin: 5px 1px 1px;
    cursor: pointer;
}

.commonWebUploader .filelist div.file-panel span.rotateLeft {
    background-position: 0 -24px;
}
.commonWebUploader .filelist div.file-panel span.rotateLeft:hover {
    background-position: 0 0;
}

.commonWebUploader .filelist div.file-panel span.rotateRight {
    background-position: -24px -24px;
}
.commonWebUploader .filelist div.file-panel span.rotateRight:hover {
    background-position: -24px 0;
}

.commonWebUploader .filelist div.file-panel span.cancel,
.editableGallery .filelist div.file-panel span.cancel {
    background-position: -48px -24px;
}
.commonWebUploader .filelist div.file-panel span.cancel:hover,
.editableGallery .filelist div.file-panel span.cancel:hover {
    background-position: -48px 0;
}

.commonWebUploader .statusBar {
    height: 55px;
    border-top: 1px solid #dadada;
    padding: 0 20px;
    line-height: 55px;
    vertical-align: middle;
    position: relative;
}

.commonWebUploader .statusBar .progress {
    border: 1px solid #1483d8;
    width: 198px;
    background: #fff;
    height: 18px;
    position: relative;
    display: inline-block;
    text-align: center;
    line-height: 20px;
    color: #6dbfff;
    position: relative;
    margin: 0 10px 0 0;
}
.commonWebUploader .statusBar .progress span.percentage {
    width: 0;
    height: 100%;
    left: 0;
    top: 0;
    background: #1483d8;
    position: absolute;
}
.commonWebUploader .statusBar .progress span.text {
    position: relative;
    z-index: 10;
}

.commonWebUploader .statusBar .info {
    display: inline-block;
    font-size: 14px;
    color: #666666;
}

.commonWebUploader .statusBar .btns {
    position: absolute;
    top: 10px;
    right: 20px;
    line-height: 32px;
}

.commonWebUploader .statusBar .btns .addFileBtn {
    display: inline-block;
    float: left;
}

.commonWebUploader .statusBar .btns .webuploader-pick,
.commonWebUploader .statusBar .btns .uploadBtn,
.commonWebUploader .statusBar .btns .uploadBtn.state-uploading,
.commonWebUploader .statusBar .btns .uploadBtn.state-paused {
    background: #ffffff;
    border: 1px solid #cfcfcf;
    color: #565656;
    padding: 0 18px;
    display: inline-block;
    border-radius: 3px;
    margin-left: 10px;
    cursor: pointer;
    font-size: 14px;
    float: left;
}
.commonWebUploader .statusBar .btns .webuploader-pick-hover,
.commonWebUploader .statusBar .btns .uploadBtn:hover,
.commonWebUploader .statusBar .btns .uploadBtn.state-uploading:hover,
.commonWebUploader .statusBar .btns .uploadBtn.state-paused:hover {
    background: #f0f0f0;
}

.commonWebUploader .statusBar .btns .uploadBtn {
    background: #00b7ee;
    color: #fff;
    border-color: transparent;
}
.commonWebUploader .statusBar .btns .uploadBtn:hover {
    background: #00a2d4;
}

.commonWebUploader .statusBar .btns .uploadBtn.disabled {
    pointer-events: none;
    opacity: 0.6;
}
style.css

官網下載一個webuploader.js

自定義editableGallery.js(這個js為編輯圖片所用),再引入commonWebUploader.js(我上一篇已經貼出了代碼,這個js為上傳圖片所用)

/* 
 * 可編輯的相冊
 * 
 */
( function( $ ) {
    
    var EditableGallery = function () {
    }
    
    EditableGallery.prototype.addDeletedUrl = function (deletedUrl) {
        if (!this.deletedUrls) {
            this.deletedUrls = [];
        }
        this.deletedUrls.push(deletedUrl);
    }
    
    EditableGallery.prototype.getDeletedUrls = function () {
        return this.deletedUrls;
    }
    
    EditableGallery.prototype.clearDeletedUrls = function () {
        this.deletedUrls = [];
    }
    
    $.fn.extend({
        editableGallery: function( option ) {
            
            var defaults = {
                urls : [],
                canDelete : false
            };
            
            var plugin = this;
            
            var value,
                args = Array.prototype.slice.call(arguments, 1);
            
            // 樣式可以掛到“上傳”那邊。
            function makeGallery($wrap, urls, canDelete) {
                var data = $wrap.data('editableGallery');
                data['clearDeletedUrls'].apply(data);
                var $fileList = $('<ul class="filelist"></ul>');
                $wrap.empty().append($fileList);
                $.each(urls, function(index, element) {
                    // fancybox放大圖片。data-fancybox-group設置為一個獨特的值,確保“放大后切換圖片時只顯示這一組圖片”。
                    var $li = $('<li id="' + index + '">' +
                        '<p class="imgWrap"><a class="fancybox" data-fancybox-group="gallery' + $wrap.attr("id")
                        + '" href="' + element + '"><img src="' + element + '"></a></p>' +
                        '</li>');
                    
                    if (canDelete) {
                        var $btns = $('<div class="file-panel">' +
                            '<span class="cancel">刪除</span>' +
                            '</div>').appendTo( $li );
                        $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();

                            switch ( index ) {
                                case 0:
                                    data['addDeletedUrl'].apply(data, [element]);
                                    $li.off().find('.file-panel').off().end().remove();
                                    return;
                                
                            }

                        });
                    }
                    
                    $li.appendTo($fileList);
                });
            }
            
            plugin.each( function() {
                var $this = $( this ),
                    data = $this.data('editableGallery'),
                    options =  $.extend(defaults, typeof option === 'object' && option);
                if ( $this ) {
                    if (typeof option === 'string') {
                        if (!data) {
                            return;
                        }
                        
                        value = data[option].apply(data, args);
                    } else {
                        if (!data) {
                            $this.data('editableGallery', (data = new EditableGallery()));
                        }
                        makeGallery($this, options.urls, options.canDelete);
                    }
                }
            });
            
            return typeof value === 'undefined' ? plugin : value;
            
        } // end editableGallery
    });
}( jQuery ));
editableGallery.js

2.jsp頁面

           <div id="moduleGallery" class="editableGallery"></div>             //存儲上次上傳的圖片
                   <div id="uploader" class="commonWebUploader">              //提供再次上傳
                            <div class="queueList">
                                <div id="dndArea" class="placeholder">
                                    <div id="filePicker"></div>
                                    <p>或將照片拖到這里,單次最多可選10張</p>
                                    <p style="font-size: 12px;margin-top: 2px;">提示:請上傳3M以下,格式為jpg、png、bmp格式圖片,以保證獲得最佳效果</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.頁面js代碼(具體的參數解釋,上一篇有介紹),這一部分主要是為了監控什么時候圖片全部上傳完畢

//上傳圖片
var wuploader;
$(document).ready(function() {     
    // 初始化上傳插件
    initWebUploaderUI();

});

  //初始化上傳插件
function initWebUploaderUI(){     
        // WebUploader實例
        wuploader = CommonWebUploader.initWebUploader('#uploader', '#filePicker', '#filePicker2', 'uploadModuleOrFunctionFile');
        // 所有文件上傳結束時
        wuploader.on( 'uploadFinished', function() {            
            var stats = wuploader.getStats();
            // 全部上傳成功
            if (!stats.uploadFailNum) {
                
               alert("保存成功!");
            }
        });
     
}

4.點擊編輯按鈕時展示的數據

function editModule(moduleID){
     $.ajax({
         cache: true,
         type: "POST",
         url:"module/getModuleFunctionByID",
         data:{
             moduleID:moduleID
         },
         error: function(request) {
               alert("連接失敗!"); 
            },
         success: function(data){
         
                                     
            // 現有圖片
            $('#moduleGallery').editableGallery({

//此處可根據自己的需要進行修改參數,我這里第一個參數:一條數據的ID,第二個參數:這條數據的類型(不需要,可不要),第三個參數:這條數據對應的多張圖片的路徑集合 urls: handleFileUrl(moduleID, 2, data.moduleFilePathList), //2表示模塊:文件類型 canDelete: true //這個參數定義,鼠標移動到圖片上時,顯示刪除按鈕 (查看時,不需要編輯圖片,可不要這個屬性) }); } }); }

//請求顯示圖片的方法(此處存的是絕對路徑,文件以流的方式顯示在頁面)

function handleFileUrl(ownerID,fileType, paths) {
    var result = [];
    if (paths) {
        $.each(paths, function(index, value) {
            result.push("seeModuleOrFunctionFile/" + ownerID + "/" +fileType+ "/" + value);    //seeModuleOrFunctionFile為后台請求圖片的方法
        });
    }
    return result;
}

5.請求顯示在頁面的方法

        /**
         * @param ownerID  (id)
         * @param fileType:文件類型
         * @param fileName:文件名稱
         * @return
         * @throws FileNotFoundException
         */
        @RequestMapping(path="/seeModuleOrFunctionFile/{ownerID}/{fileType}/{fileName:[a-zA-Z0-9\\.\\-]+}", method=RequestMethod.GET)
        public ResponseEntity<InputStreamResource> seeModuleOrFunctionFile(@PathVariable(name="ownerID") String ownerID,@PathVariable(name="fileType")  int fileType, @PathVariable(name="fileName")  String fileName) 
                throws FileNotFoundException{
            // TODO 如果文件不存在?異常處理
            Path path;                 //存儲圖片的路徑,這里存的數據為:一條數據id為文件夾名稱,文件夾里面放的此條id對應的多張圖片 if(fileType==ProductModuleFunctionFile.TYPE_MODULE){
                 path = Paths.get(uploadPathProperties.getModuleFile(), ownerID, fileName);         //uploadPathProperties中定義實體類,定義一個資源文件test.properties中定義不同的路徑(也可在這里直接定義路徑)
            }else{
                path = Paths.get(uploadPathProperties.getFunctionFile(), ownerID, fileName);
            }

            File file = path.toFile();
            
            String mimeType = URLConnection.guessContentTypeFromName(file.getName());
            if (mimeType == null) {
                mimeType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
            }
            
            HttpHeaders respHeaders = new HttpHeaders();
            respHeaders.set(HttpHeaders.CONTENT_TYPE, mimeType);
            respHeaders.setContentLength(file.length());
            String encodedFileName = file.getName();
            try {
                encodedFileName = URLEncoder.encode(encodedFileName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                logger.error("文件名編碼錯誤!", e);
            }
            respHeaders.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + encodedFileName + "\"");            
            InputStreamResource isr = new InputStreamResource(new FileInputStream(file));
            return new ResponseEntity<InputStreamResource>(isr, respHeaders, HttpStatus.OK);
        }

6.編輯完圖片后,點擊保存按鈕時,調用的方法(這里是先保存的其他數據,再保存的上傳的圖片的數據

     var delUrls = parseUrls($('#moduleGallery').editableGallery('getDeletedUrls'));           //保存之前的圖片中,被刪除的圖片的路徑
         var params={"moduleID":moduleID,"moduleTitle":$("#moduleTitle").val(),"beforeDelPathList":delUrls};     //要傳到后台的參數
                 
$.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();   // 上傳文件
                  }
              });


//對圖片的路徑進行處理(我的數據庫里只存了圖片的名字) function parseUrls(fileUrls) { var result = []; if (fileUrls) { $.each(fileUrls, function(index, value) { result.push(value.substring(value.lastIndexOf("/") + 1)); }); } return result; }

7.后台的上傳方法,和上一篇是一樣的(上一篇中已經貼出代碼)(可根據自己的業務邏輯進行修改)

  我這里獲取之前圖片中被刪除的圖片路徑,是為了在后台進行刪除數據庫中存的圖片的數據,和服務器的圖片,然后保存再次上傳的圖片

8.最后點擊編輯時顯示效果如下,上面是上一次上傳的圖片,鼠標放上去時,顯示刪除按鈕,可進行刪除。下面可再次上傳圖片

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM