webupload附件上传插件

webupload附件上传插件

(function (window, $, undefined) {
var _Core = function () {};
  window.$Core = new _Core();

    var config = function () {
        return {
            //附件上传单文件大小限制
            WebUpload_fileSingleSizeLimit: 50 * 1024 * 1024,
            //ajax请求超时时间
            ajaxTimeout: 500000
        };
    };
    $Core.Config = new config();
})(window, jQuery);
  <table style="margin: auto" id="submit_table">
                <tr>
                        <td colspan="9">
                        <label style="font-size:15px;">  上传附件:</label>
                            <input id="attchmentId" name="attchmentId" />
                        </td>
                    </tr>
  </table>


$("#attchmentId").webupload({ disabled: false, preview: false });
		if (pagetype == "show") {
			 $("input").attr("readonly", "readonly");
	            $(".easyui-combobox").combo('readonly', true);
	            $(".easyui-combotree").combotree('readonly', true);
	            $('.easyui-textbox').textbox('readonly');
	            $(".easyui-my97").my97('disable');
	            $("#attchmentId").webupload({ disabled: true, preview: true });
		}
(function ($) {
    var DOWN_PATH = $Core.SERVICEPATH() + "plugs/attachment/get/";
    var UP_PATH = $Core.SERVICEROOT() + 'zuul/plugs/attachment/fileUpload';
    //WebUploader.Uploader.register({
    //    "before-send-file": "beforeSendFile"
    //}, {
    //        beforeSendFile: function (file) {

    //            var task = new $.Deferred();
    //            (new WebUploader.Uploader()).md5File(file, 0, 10 * 1024 * 1024).progress(function (percentage) {

    //            }).then(function (val) {
    //                //console.log("用时:" + ((new Date()).getTime() - d1.getTime()));
    //                console.log(file.id + "md5:" + val);
    //                //task.reject();
    //                task.resolve();
    //            });
    //            return $.when(task);
    //        }
    //    });

    function create(target) {
        var state = $.data(target, 'webupload');
        var opts = state.options;

        var t = $(target);
        var $htmlUpload = t.next().find(".uploader");
        if (!t.hasClass("webupload-f")) {
            t.addClass("webupload-f");
            var name = t.attr("name");
            t.attr("textboxname", name).removeAttr("name");
            var $textbox = $('<input type="hidden" class="textbox-value" value="">');
            $textbox.attr("name", name);

            $htmlUpload = $('<div class="webupload"><div class="uploader">' +
                '<div class="command">' +
                '<div class="uploader-picker">上传文件</div> ' +
                //'<button type="button" class="uploader-up btn btn-primary">开始上传</button> ' +
                //'<button type="button" class="uploader-retry btn btn-primary">全部重试</button> ' +
                // '<button type="button" class="uploader-clear ">' +
                //    '<i class="glyphicon glyphicon-trash"></i> 清空所有</button>' +
                '</div><div class="uploader-list"></div></div></div>'
            );
            $htmlUpload.append($textbox);
            t.hide();
            t.after($htmlUpload);

            var $command = $htmlUpload.find(".command");
            var $picker = $htmlUpload.find(".uploader-picker");
            var $uploaderList = $htmlUpload.find(".uploader-list");
            opts.pick = $picker[0];
             
            var uploader = WebUploader.create(opts);
            uploader.on('uploadBeforeSend',
                function(object, data, header) {
                    var user = $Core.USER();
                    header = $.extend(header,
                        {
                            'token': user.TOKEN,
                            'appid': user.APP_ID
                        });
                });
            //当文件被加入队列以后触发。
            uploader.on('fileQueued',
                function(file) {
                    if (file.size > $Core.Config.WebUpload_fileSingleSizeLimit) {
                        alert(file.name +
                            "单文件不能超过" +
                            WebUploader.Base.formatSize($Core.Config.WebUpload_fileSingleSizeLimit, 0));
                        uploader.removeFile(file, true);
                        return false;
                    }
                    var $li = createFileItem(uploader, file, opts);
                    $uploaderList.append($li);
                });
            //当文件被移除队列后触发。
            uploader.on("fileDequeued",
                function(file) {
                    $("#" + file.id).fadeOut(function() {
                        $(this).remove();
                        changevalue(target);
                    });
                    //console.log(file);
                });
            // 文件上传过程中创建进度条实时显示。
            uploader.on('uploadProgress',
                function(file, percentage) {
                    var $li = $('#' + file.id),
                        $percent = $li.find('.progress span');
                    //console.log("percentage:", percentage);
                    // 避免重复创建
                    if (!$percent.length) {
                        $percent = $('<p class="progress"><span></span></p>')
                            .appendTo($li)
                            .find('span');
                    }

                    $percent.css('width', percentage * 100 + '%');
                });
            // 文件上传成功,给item添加成功class, 用样式标记上传成功。
            uploader.on('uploadSuccess',
                function(file, response) {
                    //console.log(response);
                    var $fileitem = $('#' + file.id);
                    if (response.code != undefined && response.code === 0) {
                        //response.data.attachmentId

                        $fileitem.attr("attachmentId", response.data.attachmentId);
                        var $attachmentsize = $fileitem.find(".attachment-size");
                        $attachmentsize.append('<a title="下载" href = "' +
                            DOWN_PATH +
                            response.data.attachmentId +
                            '" class="btn btn-default btn-xs pull-right" > ' +
                            '<i class="fa fa-cloud-download" ></i> ' +
                            '</a>');
                    }
                    $fileitem.addClass('upload-state-done').find(".error").remove();
                    changevalue(target);
                });

            // 文件上传失败,现实上传出错。
            uploader.on('uploadError',
                function(file, reason) {
                    //console.log(reason);
                    var $li = $('#' + file.id),
                        $error = $li.find('div.error');

                    // 避免重复创建
                    if (!$error.length) {
                        $error = $('<div class="error"></div>').appendTo($li);
                        "".format("123");
                    }

                    $error.text('上传失败' + reason);
                });

            // 完成上传完了,成功或者失败,先删除进度条。
            uploader.on('uploadComplete',
                function(file) {
                    $('#' + file.id).find('.progress').remove();
                });
            //当所有文件上传结束时触发。
            uploader.on("uploadFinished",
                function() {

                });
            state.uploader = uploader;

        }
        if (opts.disabled === true) {
            disable(target);
        } else {
            enable(target);
        }
        if (opts.preview === false) {
            $htmlUpload.find(".uploader-list").addClass("nopreview");
        }
    }
    /*
    '<a href = "#" class="btn btn-default btn-xs pull-right" > ' +
        '<i class="fa fa-cloud-download" ></i> ' +
        '</a>' +
    * /
    /**
     * 
     * @param {any} uploader
     * @param {any} file
     */
    function createFileItem(uploader, file, opts) {
        var $li = $((
            '<div id="{0}" class="file-item">' +
            '<span class="mailbox-attachment-icon"><i class= "fa fa-file-pdf-o" ></i></span>' +
            ' <div class="info">' +
            '<i class= "fa fa-paperclip" ></i > ' +
            '<a href="#" class="attachment-name" title="{1}">{1}</a> ' +
            '<span class="attachment-size"> ' +
            '<span>{2}</span> ' +
            '<a href="#" class="btn btn-default btn-xs pull-right filedel">' +
            '<i class="fa fa-close"></i>' +
            '</a>' +
            '</span>' +
            '</div >' +
            '</div>').format(file.id, file.name, WebUploader.Base.formatSize(file.size))
        ),

            $close = $li.find(".filedel"),
            $attachmentIcon = $li.find(".mailbox-attachment-icon"),
            $attachmentIcon_icon = $attachmentIcon.find(".fa"),
            $attachmentsize = $li.find(".attachment-size")
            ;
       
        if (file.attachmentId) {
            $li.attr("attachmentId", file.attachmentId);
            $attachmentsize.append('<a title="下载" href = "' + DOWN_PATH + file.attachmentId +
                '" class="btn btn-default btn-xs pull-right" > ' +
                '<i class="fa fa-cloud-download" ></i> ' +
                '</a>');
        }
        $close.click(function () {
            var fileId = $(this).parent().parent().parent().attr("id");
            //alert(fileId);
            //uploader.cancelFile(fileId);
            uploader.removeFile(fileId, true);

        });
        //var iconclass = "icon-new_file";
        if (opts.preview === true) {
            switch (file.ext.toLowerCase()) {
                case "gif":
                case "jpg":
                case "jpeg":
                case "bmp":
                case "png":

                    $attachmentIcon.addClass("has-img").html("");
                    var $img = $("<img>").appendTo($attachmentIcon);
                    if (file.attachmentId) {
                        $img.attr("src", DOWN_PATH + file.attachmentId);
                    } else {
                        uploader.makeThumb(file,
                            function (error, src) {
                                if (error) {
                                    $img.replaceWith('<span>不能预览</span>');
                                    return;
                                }
                                $img.attr('src', src);
                            },
                            500,
                            460);
                    }
                    $img.click(function () {
                        layer.open({
                            type: 1,
                            title: false,
                            closeBtn: 0,
                            area: '50%',
                            skin: 'layui-layer-nobg', //没有背景色
                            shadeClose: true,
                            content: '<img src="' + $img.attr("src") + '" style="width:100%" />'
                        });
                    });
                    break;
                case "docx":
                case "dox":
                    $attachmentIcon_icon.attr("class", "fa fa-file-word-o");
                    break;
                case "xlsx":
                case "xls":
                    $attachmentIcon_icon.attr("class", "fa fa-file-excel-o");
                    break;
                case "pptx":
                case "ppt":
                    $attachmentIcon_icon.attr("class", "fa fa-file-powerpoint-o");
                    break;
                case "zip":
                case "rar":
                    $attachmentIcon_icon.attr("class", "fa fa-file-zip-o");
                    break;
                case "mp4":
                case "avi":
                case "mkv":
                case "mov":
                case "m4v":
                case "3gp":
                case "wmv":
                case "rm":
                case "rmvb":
                    $attachmentIcon_icon.attr("class", "fa fa-file-video-o");
                    break;
                case "mp3":
                case "wma":
                case "wav":
                case "ape":
                case "aac":
                case "flac":
                    $attachmentIcon_icon.attr("class", "fa fa-file-audio-o");
                    break;
                case "txt":
                case "text":
                    $attachmentIcon_icon.attr("class", "fa fa-file-text-o");
                    break;
                default:
                    $attachmentIcon_icon.attr("class", "fa fa-file-o");
                    break;
            }
        }
        else
            $attachmentIcon.hide();
        return $li;
    }

    function changevalue(target) {
        var t = $(target);
        var htmluploader = t.next();
        var uploderList = htmluploader.find(".uploader-list");
        var $textbox = htmluploader.find(".textbox-value");

        var fileItems = uploderList.find("[attachmentId]");

        var fileid = [];
        $.each(fileItems, function (i, item) {
            var n = $(item);
            fileid.push(n.attr("attachmentId"));
        });
        $textbox.val(fileid.join(","));
    }
    function getstate(target) {
        return $.data(target, 'webupload');
    }

    function setValue(target, value) {
        var t = $(target);
        var state = getstate(target);
        var uploader = state.uploader;
        var opts = state.options;
        var $htmlUpload = t.next().find(".uploader-list");
        $htmlUpload.empty();
        if (value) {
            $.get("/plugs/attachment/getByIds/" + value,
                function (result) {
                    if (result.data) {
                        $.each(result.data,function (i, n) {
                                if (n != null)
                                    $htmlUpload.append(createFileItem(uploader,
                                        {
                                            id: n.attachmentId,
                                            name: n.fileName,
                                            size: n.fileSize,
                                            attachmentId: n.attachmentId,
                                            ext: n.attachmentType.replace(".", "")
                                        },
                                        opts));
                            });
                        //t.combo("setText", fileNames.join(","));
                    }
                    changevalue();
                });
        }
        changevalue();
        t.next().find(".textbox-value").val(value);
    }
    function getValue(target) {
        var t = $(target);
        //otps = $.data(target, 'webupload'),
        //  uploader = otps.uploader;
        var htmluploader = t.next();
        var $textbox = htmluploader.find(".textbox-value");
        return $textbox.val();
    }
    function isInProgress(target) {
        var t = $(target);
        var state = getstate(target),
            uploader = state.uploader;
        return uploader.isInProgress();
    }

    function disable(target) {
        var t = $(target);
        var state = getstate(target);
        var opts = state.options;
        opts.disabled = true;
        var htmluploader = t.next().find(".uploader");
        htmluploader.addClass("disabled");
        //htmluploader.find(".filedel").hide();
    }

    function enable(target) {
        var t = $(target);
        var state = getstate(target);
        var opts = state.options;
        opts.disabled = false;
        var htmluploader = t.next().find(".uploader");
        htmluploader.removeClass("disabled");
        //htmluploader.find(".filedel").show();
    }

    function getUploader(target) {
        var state = getstate(target);
        return state.uploader;
    }

    $.fn.webupload = function (options, param) {
        if (typeof options == "string") {
            var method = $.fn.webupload.methods[options];
            if (method) {
                return method(this, param);
            }
        }
        options = options || {};
        return this.each(function () {
            var state = $.data(this, "webupload");
            if (state) {
                $.extend(state.options, options);
            } else {
                $.data(this, "webupload",
                    {
                        options: $.extend({}, $.fn.webupload.defaults, $.fn.webupload.parseOptions(this), options)
                    });
            }
            create(this);
        });
    };

    $.fn.webupload.methods = {
        options: function (jq) {
            var opts = $.data(jq[0], 'webupload').options;
            return opts;
        },
        setValue: function (jq, value) {
            return jq.each(function () { setValue(this, value); });

        },
        getValue: function (jq) {
            return getValue(jq[0]);
        },
        isInProgress: function (jq) {
            return isInProgress(jq[0]);
        },
        disable: function (jq) {
            return jq.each(function () { disable(this); });
        },
        enable: function (jq) {
            return jq.each(function () { enable(this); });
        },
        uploader: function(jq) {
            return getUploader(jq[0]);
        }
    };
    $.fn.webupload.parseOptions = function (target) {
        return $.extend({}, $.parser.parseOptions(target, [
            "dnd", "disableGlobalDnd", "paste", "pick", "accept", "thumb", "compress", "runtimeOrder",
            "formData", "fileVal", "method", "sendAsBinary",
            {
                auto: "boolean", prepareNextFile: "boolean", chunked: "boolean", duplicate: "boolean",
                preview: "boolean"
            },
            {
                chunkSize: "number", chunkRetry: "number", threads: "number",
                fileNumLimit: "number", fileSizeLimit: "number", fileSingleSizeLimit: "number"
            }
        ]));
    };

    $.fn.webupload.defaults = {

        // swf文件路径
        swf: '/Content/webuploader/Uploader.swf',
        // 文件接收服务端。
        server: UP_PATH,
        // 选择文件的按钮。可选。
        // 内部根据当前运行是创建,可能是input元素,也可能是flash.
        //pick: '#picker',
        // 自动上传。
        auto: true,
        //compress: {
        //    // 图片质量,只有type为`image/jpeg`的时候才有效。
        //    quality: 95,
        //    // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false.
        //    allowMagnify: false,
        //    // 是否允许裁剪。
        //    crop: false,
        //    // 是否保留头部meta信息。
        //    preserveHeaders: true,
        //    // 如果发现压缩后文件大小比原来还大,则使用原来图片
        //    // 此属性可能会影响图片自动纠正功能
        //    noCompressIfLarger: false,
        //    // 单位字节,如果图片大小小于此值,不会采用压缩。
        //    compressSize: 0
        //},
        //chunked: true,
        fileVal: "fileName",
        preview: true, //是否显示图标预览
        prepareNextFile: true,
        accept: [{
            title: 'file',
            extensions: 'doc,docx,pdf,xls,xlsx,ppt,pptx,gif,jpg,jpeg,bmp,png,rar,zip,txt,text',
            mimeTypes: '.doc,.docx,.pdf,.xls,.xlsx,.ppt,.pptx,.gif,.jpg,.jpeg,.bmp,.png,.rar,.zip,.txt,.text'
        }]
        //单文件限制大小
        //fileSingleSizeLimit: 1024 * 1024 * 5,
    };

    $.parser.plugins.push("webupload");

    if ($.fn.form) {
        $.fn.form.defaults.fieldTypes.unshift("webupload");
        //$.array.insert($.fn.form.comboList, 0, "my97");
    }
})(jQuery);
@Controller
@RequestMapping("/attachment")
public class AttachmentController  extends BaseController<AttachmentService,Attachment> {
	@Autowired
	private AttachmentVOService attachmentVOService;
	/**
     * 实现文件上传
     * */
    @RequestMapping("fileUpload")
    @ResponseBody
    public AssembleJSON fileUpload(@RequestParam("fileName") MultipartFile file){
        AssembleJSON json = null;
        if(file.isEmpty()){
           throw new CntenException(this,"-001","文件获取失败");
        }
        Attachment attachment = null;
        try {
            attachment = saveAttachment(file);
            json = AssembleJSON.SUCCESS(attachment);
        } catch (Exception e) {
            //e.printStackTrace();
            json = AssembleJSON.FAILURE("附件存储异常",e.getMessage());
        }
        return json;
    }


    public Attachment saveAttachment(MultipartFile file) throws Exception{
        Attachment attachment = new Attachment();
        attachment.setFileName(file.getOriginalFilename());
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),file.getOriginalFilename().length());
        attachment.setAttachmentType(fileType);
        attachment.setIsDelete(0);
        //attachment.setUserId(getCurrUserData().getUserId());
        attachment.setAttachmentContent(file.getBytes());
        attachment.setFileSize((int)file.getSize());
        attachment.setCreateDate(new Date());
        attachment =  service.insert(attachment);
        attachment.setAttachmentContent(null);
        return attachment;
    }

    /**
     * 实现多文件上传
     *
     * 多文件上传,只返回成功。返回结果包含多个文件存储的结果,如果某个结果为null 就证明该文件存储失败
     * */
    @RequestMapping("multiFileUpload")
    @ResponseBody
    public AssembleJSON multiFileUpload(HttpServletRequest request){
        List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("fileName");
        if(files.size()<=0){
            throw new CntenException(this,"-001","文件获取失败");
        }
        List<Attachment> dataList = new ArrayList<Attachment>();
        Attachment attachment = null;
        for (MultipartFile file: files) {
            try {
                attachment =  saveAttachment(file);
            } catch (Exception e) {
                e.printStackTrace();
                attachment = new Attachment();
            }
            dataList.add(attachment);
        }
        return AssembleJSON.SUCCESS(dataList);
    }

    @GetMapping("/get/{attId}")
    public void download(@PathVariable Integer attId, HttpServletResponse response) throws IOException {
		Attachment attachment = service.getById(attId);
        String fileName = new String(attachment.getFileName().getBytes("UTF-8"),"ISO8859-1");//中文需要编码下
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.addHeader("Content-Type","application/octet-stream;charset=UTF-8");
        ServletOutputStream out = response.getOutputStream();
        out.write(attachment.getAttachmentContent());
        out.flush();
        out.close();
    }
  
    @GetMapping("/getByIds/{attIds}")
    @ResponseBody
    public AssembleJSON getVOByIds(@PathVariable String attIds){
    	if("null".equals(attIds) || "".equals(attIds)){
    		return AssembleJSON.FAILURE("参数错误");
    	}
    	String[] strings = attIds.split(",");
    	List<AttachmentVO> list = new ArrayList<>();
    	for(String id : strings){
    		AttachmentVO attachmentVO = attachmentVOService.getById(Integer.parseInt(id));
    		list.add(attachmentVO);
    	}
    	return AssembleJSON.SUCCESS(list);
    }

补充

var EditView = function(){
this.uploadUrl = getUploadUrl();
this.init = function(){
 function getUploadUrl() {
        var serviceUrl = $Core.SERVICEPATH();
        var preffix = serviceUrl.substring(0,serviceUrl.lastIndexOf("cnten"));
        var uploadUrl = preffix + "zuul/cnten/plugs/attachment/fileUpload";
        return uploadUrl;
    }
};

function imgShow(outerdiv, innerdiv, bigimg, _this){
    var src = _this.attr("src");//获取当前点击的pimg元素中的src属性
    $(bigimg).attr("src", src);//设置#bigimg元素的src属性

    /*获取当前点击图片的真实大小,并显示弹出层及大图*/
    $("<img/>").attr("src", src).load(function(){
        var windowW = $(window).width();//获取当前窗口宽度
        var windowH = $(window).height();//获取当前窗口高度
        var realWidth = this.width;//获取图片真实宽度
        var realHeight = this.height;//获取图片真实高度
        var imgWidth, imgHeight;
        var scale = 0.8;//缩放尺寸,当图片真实宽度和高度大于窗口宽度和高度时进行缩放

        if(realHeight>windowH*scale) {//判断图片高度
            imgHeight = windowH*scale;//如大于窗口高度,图片高度进行缩放
            imgWidth = imgHeight/realHeight*realWidth;//等比例缩放宽度
            if(imgWidth>windowW*scale) {//如宽度扔大于窗口宽度
                imgWidth = windowW*scale;//再对宽度进行缩放
            }
        } else if(realWidth>windowW*scale) {//如图片高度合适,判断图片宽度
            imgWidth = windowW*scale;//如大于窗口宽度,图片宽度进行缩放
            imgHeight = imgWidth/realWidth*realHeight;//等比例缩放高度
        } else {//如果图片真实高度和宽度都符合要求,高宽不变
            imgWidth = realWidth;
            imgHeight = realHeight;
        }
        $(bigimg).css("width",imgWidth);//以最终的宽度对图片缩放

        var w = (windowW-imgWidth)/2;//计算图片与窗口左边距
        var h = (windowH-imgHeight)/2;//计算图片与窗口上边距
        $(innerdiv).css({"top":h, "left":w});//设置#innerdiv的top和left属性
        $(outerdiv).fadeIn("fast");//淡入显示#outerdiv及.pimg
    });

    $(outerdiv).click(function(){//再次点击淡出消失弹出层
        $(this).fadeOut("fast");
    });
}

    $("#upload").click(function () {
        var imgId = $("#imgId").val();
        if(imgId == null || imgId == ""){
            //未上传过
            var formData = new FormData();
            formData.append("fileName", $("[name=fileName]")[0].files[0]);
            $.ajax({
                url: _self.uploadUrl,
                type: "POST",
                data: formData,
                /**
                 *必须false才会自动加上正确的Content-Type
                 */
                contentType: false,
                /**
                 * 必须false才会避开jQuery对 formdata 的默认处理
                 * XMLHttpRequest会对 formdata 进行正确的处理
                 */
                processData: false,
                success: function (data) {
                    if (data.code == 0) {
                        var attachmentId = data.data.attachmentId;
                        $Core.UI.message.success("上传成功!");
                        $("#imgId").val(attachmentId);
                        setImgPreview(attachmentId);
                    }
                    if (data.code != 0) {
                        $Core.UI.message.warning(data.msg);
                    }
                },
                error: function () {
                    $Core.UI.message.success("上传失败!");
                }
            });
        }else{
            //上传过,进行修改
            var id = $("#id").val();
            if(id == null || id == ""){
                //进行的是添加操作
                var formData = new FormData();
                formData.append("fileName", $("[name=fileName]")[0].files[0]);
                $.ajax({
                    url: _self.uploadUrl,
                    type: "POST",
                    data: formData,
                    /**
                     *必须false才会自动加上正确的Content-Type
                     */
                    contentType: false,
                    /**
                     * 必须false才会避开jQuery对 formdata 的默认处理
                     * XMLHttpRequest会对 formdata 进行正确的处理
                     */
                    processData: false,
                    success: function (data) {
                        if (data.code == 0) {
                            var attachmentId = data.data.attachmentId;
                            $.post("plugs/attVO/del?ids=" + imgId, function (data) {
                                $("#imgId").val(attachmentId);
                                setImgPreview(attachmentId);
                                $Core.UI.message.success("上传成功!");
                            });
                        }
                        if (data.code != 0) {
                            $Core.UI.message.warning(data.msg);
                        }
                    },
                    error: function () {
                        $Core.UI.message.success("上传失败!");
                    }
                });
            }else{
                //进行的是修改操作
                $.messager.confirm("提示","上传后原有图片将删除,是否上传",function (r) {
                    if(r) {
                        var formData = new FormData();
                        formData.append("fileName", $("[name=fileName]")[0].files[0]);
                        $.ajax({
                            url: _self.uploadUrl,
                            type: "POST",
                            data: formData,
                            /**
                             *必须false才会自动加上正确的Content-Type
                             */
                            contentType: false,
                            /**
                             * 必须false才会避开jQuery对 formdata 的默认处理
                             * XMLHttpRequest会对 formdata 进行正确的处理
                             */
                            processData: false,
                            success: function (data) {
                                if (data.code == 0) {
                                    var attachmentId = data.data.attachmentId;
                                    $.post("security/publicservicesuser/upd",{"id":id,"imgId":imgId}, function (data) {
                                        $("#imgId").val(attachmentId);
                                        $Core.UI.message.success("上传成功!");
                                        setImgPreview(attachmentId);
                                        //删除原有数据
                                        $.post("plugs/attVO/del?ids=" + imgId, function (data) {
                                        });
                                    });
                                }
                                if (data.code != 0) {
                                    $Core.UI.message.warning(data.msg);
                                }
                            },
                            error: function () {
                                $Core.UI.message.success("上传失败!");
                            }
                        });
                    }
                });
            }
        }
    });

    function setImgPreview(imgId) {
        var imghtml = '<th style="width: 70px">照片预览:</th>'+
            '<td style="width: 670px" colspan="7">'+
            '<img id="pimg" src="'+$Core.SERVICEPATH()+'plugs/attachment/get/'+imgId+'" style="height: 90px; width: 90px;">'+
            '</td>'
        $("#picPreview").html(imghtml);
        //查看大图
        $("#pimg").on('click',function(){
            var _this = $(this);//将当前的pimg元素作为_this传入函数
            imgShow("#outerdiv", "#innerdiv", "#bigimg", _this);
        });
    }
    <div id="outerdiv" style="position:fixed;top:0;left:0;background:rgba(0,0,0,0.7);z-index:2;width:100%;height:100%;display:none;">
        <div id="innerdiv" style="position:absolute;">
            <img id="bigimg" style="border:5px solid #fff;" src="" />
        </div>
    </div>
    <nav class="navbar navbar-default navbar-fixed-bottom" style="width: 100%">
        <div class="footcommandbar" style="vertical-align: middle; line-height: 50px;text-align: right">
            <button type="button" id="btnSave" class="btn btn-primary">
                <i class="glyphicon glyphicon-save"></i>
                保存
            </button>
        </div>
    </nav>

猜你喜欢

转载自blog.csdn.net/qq_35029061/article/details/83380278