百度WebUploader上传图片,图片回显编辑,查看

Posted 磨人小妖精

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了百度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.最后点击编辑时显示效果如下,上面是上一次上传的图片,鼠标放上去时,显示删除按钮,可进行删除。下面可再次上传图片

 

以上是关于百度WebUploader上传图片,图片回显编辑,查看的主要内容,如果未能解决你的问题,请参考以下文章

项目相关MVC中使用WebUploader进行图片预览上传以及编辑

百度图片上传插件webuploader

百度上传控件webuploader如何限制 图片尺寸大小

百度上传工具webuploader,图片上传附加参数

百度编辑器图片上传

WebUploader文件图片上传插件的使用