牛骨文教育服务平台(让学习变的简单)

自定义上传事件

如果想自定义控制图片上传完成、失败、超时时的操作,可通过配置 editor.config.uploadImgFns.onload editor.config.uploadImgFns.ontimeout editor.config.uploadImgFns.onerror 三个事件来自定义。

另外,在自定义的上传事件中,可通过editor.uploadImgOriginalName来获取图片名称(例如用作<img>alt属性),注意看代码注释。

注意,ontimeoutonerror两个事件在IE8、9下不起作用


代码示例如下:

<div id="div1">
    <p>请输入内容...</p>
</div>

<!--这里引用jquery和wangEditor.js-->
<script type="text/javascript">
    var editor = new wangEditor("div1");
    
    // 自定义load事件
    editor.config.uploadImgFns.onload = function (resultText, xhr) {
        // resultText 服务器端返回的text
        // xhr 是 xmlHttpRequest 对象,IE8、9中不支持
        
        // 上传图片时,已经将图片的名字存在 editor.uploadImgOriginalName
        var originalName = editor.uploadImgOriginalName || "";  
        
        // 如果 resultText 是图片的url地址,可以这样插入图片:
        editor.command(null, "insertHtml", "<img src="" + resultText + "" alt="" + originalName + "" style="max-width:100%;"/>");
        // 如果不想要 img 的 max-width 样式,也可以这样插入:
        // editor.command(null, "InsertImage", resultText);
    };
    
    // 自定义timeout事件
    editor.config.uploadImgFns.ontimeout = function (xhr) {
        // xhr 是 xmlHttpRequest 对象,IE8、9中不支持
        alert("上传超时");
    };
    
    // 自定义error事件
    editor.config.uploadImgFns.onerror = function (xhr) {
        // xhr 是 xmlHttpRequest 对象,IE8、9中不支持
        alert("上传错误");
    };
    
    editor.create();
</script>

以下代码,是wangEditor.js中定义的。仅供参考,请勿直接复制粘贴来用

var editor = this;
var fns = editor.config.uploadImgFns; // editor.config.uploadImgFns = {} 在config文件中定义了

// -------- 插入图片的方法 --------
function insertImg(src) {
    var img = document.createElement("img");
    img.onload = function () {
        var html = "<img src="" + src + "" style="max-width:100%;"/>";
        editor.command(null, "insertHtml", html);

        E.log("已插入图片,地址 " + src);
        img = null;
    };
    img.onerror = function () {
        E.error("使用返回的结果获取图片,发生错误。请确认以下结果是否正确:" + src);
        img = null;
    };
    img.src = src;
}

// -------- 定义load函数 --------
fns.onload || (fns.onload = function (resultText, xhr) {

    E.log("上传结束,返回结果为 " + resultText);

    if (resultText.indexOf("error|") === 0) {
        // 提示错误
        E.warn("上传失败:" + resultText.split("|")[1]);
        alert(resultText.split("|")[1]);
    } else {
        E.log("上传成功,即将插入编辑区域,结果为:" + resultText);
        // 将结果插入编辑器
        insertImg(resultText);
    }

});

// -------- 定义tiemout函数 --------
fns.ontimeout || (fns.ontimeout = function (xhr) {
    E.error("上传图片超时");
    alert("上传图片超时");
});

// -------- 定义error函数 --------
fns.onerror || (fns.onerror = function (xhr) {
    E.error("上传上图片发生错误");
    alert("上传上图片发生错误");
});