fileupload.js中的自定义模板

时间:2013-06-16 18:07:36

标签: javascript jquery jsf primefaces blueimp

我想在primefaces中自定义fileupload UI组件,其中inturn使用blueimp fileupload.js。我想用我的自定义模板覆盖默认的primefaces模板,并将渲染的模板附加到div“#errorMessage_wbMessages”而不是默认的“.fileupload-content”

我尝试将uploadContent和uploadTemplate设置如下,但它不起作用。

自定义模板

fileLoader是fileupload组件

中属性widgetVar的给定名称
fileLoader.uploadContent = $("#errorMessage_wbMessages");
    fileLoader.cfg.uploadTemplate = '<div class="ui-message-fatal ui-corner-all"><a href="#" class="ui-messages-close" onclick="$(this).parent().slideUp();return false;"><span class="ui-icon ui-icon-close"></span></a><span class="ui-messages-fatal-icon"></span><ul><li><span class="ui-messages-fatal-summary">File Upload Issue :{{if error === "maxFileSize"}}File Limit exceeded{{else error === "minFileSize"}}File Limit exceeded{{else error === "acceptFileTypes"}}Invalid File{{else error === "maxNumberOfFiles"}}Max number of files exceeded.{{else}}${error}{{/if}}</span></li></ul></div>';

由primefaces

使用的fileupload.js
(function(a) {
    a.widget("blueimpUI.fileupload", a.blueimp.fileupload, {options: {autoUpload: false,maxNumberOfFiles: undefined,maxFileSize: undefined,minFileSize: 1,acceptFileTypes: /.+$/i,previewFileTypes: /^image\/(gif|jpeg|png)$/,previewMaxWidth: 80,previewMaxHeight: 80,previewAsCanvas: true,uploadTemplate: a("#template-upload"),downloadTemplate: a("#template-download"),dataType: "json",add: function(d, c) {
                var b = a(this).data("fileupload");
                b._adjustMaxNumberOfFiles(-c.files.length);
                c.isAdjusted = true;
                c.isValidated = b._validate(c.files);
                c.context = b._renderUpload(c.files).appendTo(a(this).find(".files")).fadeIn(function() {
                    a(this).show()
                }).data("data", c);
                if ((b.options.autoUpload || c.autoUpload) && c.isValidated) {
                    c.jqXHR = c.submit()
                }
            },send: function(d, c) {
                if (!c.isValidated) {
                    var b = a(this).data("fileupload");
                    if (!c.isAdjusted) {
                        b._adjustMaxNumberOfFiles(-c.files.length)
                    }
                    if (!b._validate(c.files)) {
                        return false
                    }
                }
                if (c.context && c.dataType && c.dataType.substr(0, 6) === "iframe") {
                    c.context.find(".ui-progressbar").progressbar("value", parseInt(100, 10))
                }
            },done: function(d, c) {
                var b = a(this).data("fileupload");
                if (b) {
                    if (c.context) {
                        c.context.each(function(e) {
                            var f = (a.isArray(c.result) && c.result[e]) || {error: "emptyResult"};
                            if (f.error) {
                                b._adjustMaxNumberOfFiles(1)
                            }
                            a(this).fadeOut(function() {
                                b._renderDownload([f]).css("display", "none").replaceAll(this).fadeIn(function() {
                                    a(this).show()
                                })
                            })
                        })
                    } else {
                        b._renderDownload(c.result).css("display", "none").appendTo(a(this).find(".files")).fadeIn(function() {
                            a(this).show()
                        })
                    }
                }
            },fail: function(d, c) {
                var b = a(this).data("fileupload");
                b._adjustMaxNumberOfFiles(c.files.length);
                if (c.context) {
                    c.context.each(function(e) {
                        a(this).fadeOut(function() {
                            if (c.errorThrown !== "abort") {
                                var f = c.files[e];
                                f.error = f.error || c.errorThrown || true;
                                b._renderDownload([f]).css("display", "none").replaceAll(this).fadeIn(function() {
                                    a(this).show()
                                })
                            } else {
                                c.context.remove()
                            }
                        })
                    })
                } else {
                    if (c.errorThrown !== "abort") {
                        b._adjustMaxNumberOfFiles(-c.files.length);
                        c.context = b._renderUpload(c.files).css("display", "none").appendTo(a(this).find(".files")).fadeIn(function() {
                            a(this).show()
                        }).data("data", c)
                    }
                }
            },progress: function(c, b) {
                if (b.context) {
                    b.context.find(".ui-progressbar").progressbar("value", parseInt(b.loaded / b.total * 100, 10))
                }
            },progressall: function(c, b) {
                a(this).find(".fileupload-progressbar").progressbar("value", parseInt(b.loaded / b.total * 100, 10))
            },start: function() {
                a(this).find(".fileupload-progressbar").progressbar("value", 0).fadeIn()
            },stop: function() {
                a(this).find(".fileupload-progressbar").fadeOut()
            },destroy: function(d, c) {
                var b = a(this).data("fileupload");
                if (c.url) {
                    a.ajax(c).success(function() {
                        b._adjustMaxNumberOfFiles(1);
                        a(this).fadeOut(function() {
                            a(this).remove()
                        })
                    })
                } else {
                    c.context.fadeOut(function() {
                        a(this).remove()
                    })
                }
            }},_scaleImage: function(b, d) {
            d = d || {};
            var c = document.createElement("canvas"), e = Math.min((d.maxWidth || b.width) / b.width, (d.maxHeight || b.height) / b.height);
            if (e >= 1) {
                e = Math.max((d.minWidth || b.width) / b.width, (d.minHeight || b.height) / b.height)
            }
            b.width = parseInt(b.width * e, 10);
            b.height = parseInt(b.height * e, 10);
            if (!d.canvas || !c.getContext) {
                return b
            }
            c.width = b.width;
            c.height = b.height;
            c.getContext("2d").drawImage(b, 0, 0, b.width, b.height);
            return c
        },_createObjectURL: function(b) {
            var d = "undefined", c = (typeof window.createObjectURL !== d && window) || (typeof URL !== d && URL) || (typeof webkitURL !== d && webkitURL);
            return c ? c.createObjectURL(b) : false
        },_revokeObjectURL: function(b) {
            var d = "undefined", c = (typeof window.revokeObjectURL !== d && window) || (typeof URL !== d && URL) || (typeof webkitURL !== d && webkitURL);
            return c ? c.revokeObjectURL(b) : false
        },_loadFile: function(c, d) {
            if (typeof FileReader !== "undefined" && FileReader.prototype.readAsDataURL) {
                var b = new FileReader();
                b.onload = function(f) {
                    d(f.target.result)
                };
                b.readAsDataURL(c);
                return true
            }
            return false
        },_loadImage: function(e, g, d) {
            var f = this, c, b;
            if (!d || !d.fileTypes || d.fileTypes.test(e.type)) {
                c = this._createObjectURL(e);
                b = a("<img>").bind("load", function() {
                    a(this).unbind("load");
                    f._revokeObjectURL(c);
                    g(f._scaleImage(b[0], d))
                }).prop("src", c);
                if (!c) {
                    this._loadFile(e, function(h) {
                        b.prop("src", h)
                    })
                }
            }
        },_enableDragToDesktop: function() {
            var e = a(this), c = e.prop("href"), b = decodeURIComponent(c.split("/").pop()).replace(/:/g, "-"), d = "application/octet-stream";
            e.bind("dragstart", function(g) {
                try {
                    g.originalEvent.dataTransfer.setData("DownloadURL", [d, b, c].join(":"))
                } catch (f) {
                }
            })
        },_adjustMaxNumberOfFiles: function(b) {
            if (typeof this.options.maxNumberOfFiles === "number") {
                this.options.maxNumberOfFiles += b;
                if (this.options.maxNumberOfFiles < 1) {
                    this._disableFileInputButton()
                } else {
                    this._enableFileInputButton()
                }
            }
        },_formatFileSize: function(b) {
            if (typeof b.size !== "number") {
                return ""
            }
            if (b.size >= 1000000000) {
                return (b.size / 1000000000).toFixed(2) + " GB"
            }
            if (b.size >= 1000000) {
                return (b.size / 1000000).toFixed(2) + " MB"
            }
            return (b.size / 1000).toFixed(2) + " KB"
        },_hasError: function(b) {
            if (b.error) {
                return b.error
            }
            if (this.options.maxNumberOfFiles < 0) {
                return "maxNumberOfFiles"
            }
            if (!(this.options.acceptFileTypes.test(b.type) || this.options.acceptFileTypes.test(b.name))) {
                return "acceptFileTypes"
            }
            if (this.options.maxFileSize && b.size > this.options.maxFileSize) {
                return "maxFileSize"
            }
            if (typeof b.size === "number" && b.size < this.options.minFileSize) {
                return "minFileSize"
            }
            return null
        },_validate: function(d) {
            var c = this, b;
            a.each(d, function(e, f) {
                f.error = c._hasError(f);
                b = !f.error
            });
            return b
        },_uploadTemplateHelper: function(b) {
            b.sizef = this._formatFileSize(b);
            return b
        },_renderUploadTemplate: function(c) {
            var b = this;
            return a.tmpl(this.options.uploadTemplate, a.map(c, function(d) {
                return b._uploadTemplateHelper(d)
            }))
        },_renderUpload: function(e) {
            var d = this, c = this.options, b = this._renderUploadTemplate(e);
            if (!(b instanceof a)) {
                return a()
            }
            b.css("display", "none");
            b.find(".progress div").slice(1).remove().end().first().progressbar();
            b.find(".preview").each(function(f, g) {
                d._loadImage(e[f], function(h) {
                    a(h).hide().appendTo(g).fadeIn()
                }, {maxWidth: c.previewMaxWidth,maxHeight: c.previewMaxHeight,fileTypes: c.previewFileTypes,canvas: c.previewAsCanvas})
            });
            return b
        },_downloadTemplateHelper: function(b) {
            b.sizef = this._formatFileSize(b);
            return b
        },_renderDownloadTemplate: function(c) {
            var b = this;
            return a.tmpl(this.options.downloadTemplate, a.map(c, function(d) {
                return b._downloadTemplateHelper(d)
            }))
        },_renderDownload: function(c) {
            var b = this._renderDownloadTemplate(c);
            if (!(b instanceof a)) {
                return a()
            }
            b.css("display", "none");
            b.find(".delete button").button({text: false,icons: {primary: "ui-icon-trash"}});
            b.find("a").each(this._enableDragToDesktop);
            return b
        },_startHandler: function(d) {
            d.preventDefault();
            var b = a(this).closest(".template-upload"), c = b.data("data");
            if (c && c.submit && !c.jqXHR) {
                c.jqXHR = c.submit();
                a(this).fadeOut()
            }
        },_cancelHandler: function(d) {
            d.preventDefault();
            var b = a(this).closest(".template-upload"), c = b.data("data") || {};
            if (!c.jqXHR) {
                c.errorThrown = "abort";
                d.data.fileupload._trigger("fail", d, c)
            } else {
                c.jqXHR.abort()
            }
        },_deleteHandler: function(c) {
            c.preventDefault();
            var b = a(this);
            c.data.fileupload._trigger("destroy", c, {context: b.closest(".template-download"),url: b.attr("data-url"),type: b.attr("data-type"),dataType: c.data.fileupload.options.dataType})
        },_initEventHandlers: function() {
            a.blueimp.fileupload.prototype._initEventHandlers.call(this);
            var b = {fileupload: this};
            a(this.options.namespace + " .files td.start button").die().live("click", b, this._startHandler).live("mouseover", function() {
                a(this).addClass("ui-state-hover")
            }).live("mouseout", function() {
                a(this).removeClass("ui-state-active ui-state-hover")
            }).live("mousedown", function() {
                a(this).addClass("ui-state-active")
            }).live("mouseup", function() {
                a(this).removeClass("ui-state-active")
            });
            a(this.options.namespace + " .files td.cancel button").die().live("click", b, this._cancelHandler).live("mouseover", function() {
                a(this).addClass("ui-state-hover")
            }).live("mouseout", function() {
                a(this).removeClass("ui-state-active ui-state-hover")
            }).live("mousedown", function() {
                a(this).addClass("ui-state-active")
            }).live("mouseup", function() {
                a(this).removeClass("ui-state-active")
            });
            a(this.options.namespace + " .files td.delete button").die().live("click", b, this._deleteHandler)
        },_destroyEventHandlers: function() {
            a.blueimp.fileupload.prototype._destroyEventHandlers.call(this)
        },_initFileUploadButtonBar: function() {
            var c = this.element.find(".fileupload-buttonbar"), d = this.element.find(".files"), b = this.options.namespace;
            c.addClass("ui-widget-header ui-corner-top")
        },_destroyFileUploadButtonBar: function() {
            this.element.find(".fileupload-buttonbar").removeClass("ui-widget-header ui-corner-top");
            this.element.find(".fileinput-button").each(function() {
                var b = a(this).find("input:file").detach();
                a(this).button("destroy").append(b)
            });
            this.element.find(".fileupload-buttonbar button").unbind("click." + this.options.namespace).button("destroy")
        },_enableFileInputButton: function() {
            this.element.find(".fileinput-button input:file:disabled").each(function() {
                var c = a(this), b = c.parent();
                c.detach().prop("disabled", false);
                b.button("enable").append(c)
            })
        },_disableFileInputButton: function() {
            this.element.find(".fileinput-button input:file:enabled").each(function() {
                var c = a(this), b = c.parent();
                c.detach().prop("disabled", true);
                b.button("disable").append(c)
            })
        },_initTemplates: function() {
            if (this.options.uploadTemplate instanceof a && !this.options.uploadTemplate.length) {
                this.options.uploadTemplate = a(this.options.uploadTemplate.selector)
            }
            if (this.options.downloadTemplate instanceof a && !this.options.downloadTemplate.length) {
                this.options.downloadTemplate = a(this.options.downloadTemplate.selector)
            }
        },_create: function() {
            a.blueimp.fileupload.prototype._create.call(this);
            this._initTemplates();
            this.element.addClass("ui-widget");
            this._initFileUploadButtonBar();
            this.element.find(".fileupload-content").addClass("ui-widget-content ui-corner-bottom");
            this.element.find(".fileupload-progressbar").hide().progressbar()
        },destroy: function() {
            a.blueimp.fileupload.prototype.destroy.call(this)
        },enable: function() {
            a.blueimp.fileupload.prototype.enable.call(this);
            this.element.find(":ui-button").not(".fileinput-button").button("enable");
            this._enableFileInputButton()
        },disable: function() {
            this.element.find(":ui-button").not(".fileinput-button").button("disable");
            this._disableFileInputButton();
            a.blueimp.fileupload.prototype.disable.call(this)
        }})
}(jQuery));
PrimeFaces.widget.FileUpload = PrimeFaces.widget.BaseWidget.extend({init: function(b) {
        this._super(b);
        this.form = this.jq.parents("form:first");
        this.buttonBar = this.jq.children(".fileupload-buttonbar");
        this.uploadContent = this.jq.children(".fileupload-content");
        var a = this;
        this.cfg.uploadTemplate = '<tr class="template-upload{{if error}} ui-state-error{{/if}}"><td class="preview"></td><td class="name">${name}</td><td class="size">${sizef}</td>{{if error}}<td class="error" colspan="2">{{if error === "maxFileSize"}}' + this.getMessage(this.cfg.invalidSizeMessage, this.INVALID_SIZE_MESSAGE) + '{{else error === "minFileSize"}}' + this.getMessage(this.cfg.invalidSizeMessage, this.INVALID_SIZE_MESSAGE) + '{{else error === "acceptFileTypes"}}' + this.getMessage(this.cfg.invalidFileMessage, this.INVALID_FILE_MESSAGE) + '{{else error === "maxNumberOfFiles"}}' + this.getMessage(this.cfg.fileLimitMessage, this.FILE_LIMIT_MESSAGE) + '{{else}}${error}{{/if}}</td>{{else}}<td class="progress"><div></div></td><td class="start"><button class="ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only"><span class="ui-button-icon-left ui-icon ui-icon ui-icon-arrowreturnthick-1-n"></span><span class="ui-button-text">ui-button</span></button></td><td class="cancel"><button class="ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only"><span class="ui-button-icon-left ui-icon ui-icon ui-icon-cancel"></span><span class="ui-button-text">ui-button</span></button></td>{{/if}}</tr>';
        this.cfg.downloadTemplate = "";
        this.cfg.fileInput = $(PrimeFaces.escapeClientId(this.id + "_input"));
        this.cfg.paramName = this.id;
        this.cfg.sequentialUploads = true;
        this.cfg.dataType = "xml";
        this.cfg.namespace = this.jqId;
        this.cfg.disabled = this.cfg.fileInput.is(":disabled");
        var c = this.form.children("input[name='javax.faces.encodedURL']");
        this.cfg.url = (c.length == 1) ? c.val() : this.form.attr("action");
        $.ajaxSetup({converters: {"iframe xml": this.parseIFrameResponse}});
        this.cfg.formData = function() {
            return a.createPostData()
        };
        this.cfg.dropZone = this.cfg.dnd && !this.cfg.disabled ? this.jq : null;
        if (this.form.data().fileupload) {
            this.destroy()
        }
        this.form.fileupload(this.cfg).bind("fileuploadstart", function(f, d) {
            if (a.cfg.onstart) {
                a.cfg.onstart.call(a)
            }
        }).bind("fileuploaddone", function(f, d) {
            PrimeFaces.ajax.AjaxResponse(d.result);
            if (a.cfg.oncomplete) {
                a.cfg.oncomplete.call(a)
            }
        });
        if (this.cfg.disabled) {
            this.disable()
        }
        this.jq.show();
        PrimeFaces.skinButton(this.buttonBar.children(".ui-button"));
        this.buttonBar.children(".start.ui-button").click(function(d) {
            a.uploadContent.find(".start button").click()
        });
        this.buttonBar.children(".cancel.ui-button").click(function(d) {
            a.uploadContent.find(".cancel button").click()
        })
    },parseIFrameResponse: function(b) {
        var a = b.contents(), c = null;
        if ($.browser.mozilla || $.browser.opera || ($.browser.msie && $.browser.version == "9.0")) {
            c = '<?xml version="1.0" encoding="UTF-8"?><partial-response><changes>';
            a.find("update").each(function(d, f) {
                var h = $(f), g = h.attr("id"), e = "<![CDATA[" + h.text() + "]]>";
                c += '<update id="' + g + '">' + e + "</update>"
            });
            c += "</changes></partial-response>"
        } else {
            c = $.trim(b.contents().text().replace(/(> -)|(>-)/g, ">"))
        }
        return $.parseXML(c)
    },createPostData: function() {
        var a = this.cfg.process ? this.id + " " + this.cfg.process : this.id, b = this.form.serializeArray();
        b.push({name: PrimeFaces.PARTIAL_REQUEST_PARAM,value: "true"});
        b.push({name: PrimeFaces.PARTIAL_PROCESS_PARAM,value: a});
        b.push({name: PrimeFaces.PARTIAL_SOURCE_PARAM,value: this.id});
        if (this.cfg.update) {
            b.push({name: PrimeFaces.PARTIAL_UPDATE_PARAM,value: this.cfg.update})
        }
        return b
    },getMessage: function(a, b) {
        return a || b
    },destroy: function() {
        this.form.fileupload("destroy")
    },disable: function() {
        this.jq.children(".fileupload-buttonbar").find(".ui-button").addClass("ui-state-disabled").unbind().bind("click", function(a) {
            a.preventDefault()
        });
        this.cfg.fileInput.css("cursor", "auto")
    },INVALID_SIZE_MESSAGE: "Invalid file size.",INVALID_FILE_MESSAGE: "Invalid file type.",FILE_LIMIT_MESSAGE: "Max number of files exceeded."});

Primefaces组件

<h:form prependId="false" enctype="multipart/form-data" onclick="console.log('starting form');updateConfig(this);">
                        <p:fileUpload onclick="alert('hi')"
                            fileUploadListener="#{fileUploadController.imageUpload}"
                            mode="advanced" id="fileuploader2" process="@form" sizeLimit="2"
                            label="Upload File" invalidSizeMessage="File Limit exceeded"
                            invalidFileMessage="Invalid File" cancelLabel="Cancel"
                            auto="true" styleClass="wboardUpload" widgetVar="fileLoader"  onstart="console.log('starting');updateConfig(this);console.dir(this);console.dir(this.form.fileupload)" />
                    </h:form>

0 个答案:

没有答案