Extjs2.0的HTMLEditor的扩展(上传图片)

  Extjs是现在比较流行的一种js框架,它的功能很强大,但是也有一些缺陷。例如:Ext中的HTMLEditor就没有文件上传或者图片上传的功能。这些功能的实现需要我们来扩展Extjs的HTMLEditor控件。下面就是图片上传的一个例子:

扩展HTMLEditor控件的js文件:

HTMLEditor = Ext.extend(Ext.form.HtmlEditor, {    
    addImage : function() {  
        var editor = this;   
        var imgform = new Ext.FormPanel({   
            region : 'center',
            labelWidth : 55,
            frame : true,
            bodyStyle : 'padding:5px 5px 0',
            border : false, 
            items : [
                  {
                        xtype : 'textfield',
                        fieldLabel : '选择文件', 
                        name : 'userfile', 
                        inputType : 'file',    
                        allowBlank : false,
                        blankText : '文件不能为空',
                        height : 25,
                        anchor : '90%' 
                    }],
            buttons : [{
                text : '上传',
                type : 'submit',
                handler: insertimag
            }, {
                text : '关闭',
                type : 'submit',
                handler: function(){
                   win.hide();
                }
            }]
        })
        var win = new Ext.Window({
                    title : "上传图片",
                    width : 300,
                    height : 200,
                    border : false,
                    iconCls : 'insertpict',   
                    plain:true,
                    layout : "fit",
                    items: imgform    
                });
         win.show();   
         editor.deferFocus();  
        //添加图片
        function insertimag(){
            var furl="";
            furl=imgform.form.findField('userfile').getValue();     
            var type=furl.substring(furl.length-3).toLowerCase();
            if (furl==""||furl==null) {return;}
            if(type!='jpg'&&type!='bmp'&&type!='gif'&&type!='png'){
              Ext.Msg.alert('提示','仅支持jpg、bmp、gif、png格式的图片'); 
              return;
            } 
        //=============================================
          var msgTipe = Ext.MessageBox.show({
            title:'提示',
            width: 250,
            msg:'正在保存请稍侯.......'
         });
         Ext.Ajax.request({
            url:'../questionAction.do?method=uploadimg',      
            params: {
                furl: furl
            },
            method: 'POST',
            success: function(response,options){
              msgTipe.hide(); 
              var str = response.responseText;  
              if(str.trim()!='null'){     
                  Ext.Msg.alert('上传','上传成功!'); 
                  var element = document.createElement("img");     
                     element.src = str.trim();    
                     if(Ext.isIE) {
                      editor.win.focus();
                      var r = editor.doc.selection.createRange();
                      if(r){
                         r.collapse(true);
                         r.pasteHTML(element.outerHTML);  
                         editor.syncValue();
                         editor.deferFocus();
                      }
                       // editor.insertAtCursor(element.outerHTML);       
                     }
                     else{
                        var selection = editor.win.getSelection();  
                        if (!selection.isCollapsed) { 
                             selection.deleteFromDocument();  
                        }
                       selection.getRangeAt(0).insertNode(element);
                     }
                     imgform.form.reset();
                     win.hide();
               }else{
                 Ext.Msg.alert('警告','上传失败!');     
                 return; 
              }
            },
            failure: function(){
               msgTipe.hide();
               Ext.Msg.alert('提示','上传信息请求失败!');
            }
        });
         }
    },
    createToolbar : function(editor) {
      HTMLEditor.superclass.createToolbar.call(this, editor); 
      this.tb.insertButton(16, {   
        itemId: 'image',  
        iconCls: 'insertpict', 
        handler: this.addImage,
        scope: this,
        clickEvent: 'mousedown',
        tooltip: {
          title: 'insert img',
          text: '插入图片到编辑器',
          cls: 'x-html-editor-tip' 
        }
      });
    } 
});
Ext.reg('StarHtmleditor', HTMLEditor);
下面是应用扩展的HTMLEditor

var form = new Ext.form.FormPanel({
      title:'',    
      labelWidth: 79, 
      labelSeparator: ':', 
      buttonAlign:'center', 
      width: 700,
      autoHeight: true,
      frame: true, 
      defaulst:{
        bodyStyle: 'background-color:#FFFFFF'
      },
      items:[  
               {
                  xtype : "StarHtmleditor",  
                  name : "content",
                  id:'askcontent',  
                  fieldLabel : "问题内容",
                  allowBlank: false,
                  blankText:'问题内容不能为空!', 
                  anchor : "58%",  
                  height: 500,  
                  enableAlignments: true,
                  enableFont: true,
                  enableColors: false,
                  enableFontSize:true,  
                  enableFormat: true,  
                  enableLists: true,
                  enableSourceEdit: false,
                  fontFamilies:['宋体','隶书','黑体',"Arial","Arial Narrow","System","Tims New Roman","Verdana"], 
                  buttonTips:{
                      bold:{
                        title: 'Bold (Ctrl+B)',
                        cls: 'x-html-editor-tip',
                        text:'粗体'
                      },
                italic: {
                   title:'Italic (Ctr+I)',
                   cls: 'x-html-editor-tip',
                   text:'斜体'
                },
                underline:{
                   title:'Underline (Ctrl+U)',
                   cls: 'x-html-editor-tip',
                   text:'下划线'
                },
                increasefontsize:{
                   title:'Grow Text',
                   cls: 'x-html-editor-tip',
                   text: '增大字体'
                },
                decreasefontsize:{
                    title:'Shrink Text',
                    cls: 'x-html-editor-tip',
                    text:'缩小字体'
                },
                backcolor:{
                    title:'Text Highlight Color',
                    cls: 'x-html-editor-tip',
                    text:'背景色'
                },
                forecolor:{
                   title:'Font Color',
                   cls: 'x-html-editor-tip',
                   text:'前景色'
                },
                justifyleft:{ 
                   title:'Align Text Left',
                   cls: 'x-html-editor-tip',
                   text:'左对齐'
                },
                justifycenter:{
                   title:'Center Text',
                   cls: 'x-html-editor-tip',
                   text:'中间对齐'
                },
                justifyright:{
                   title:'Align Text Right',
                    cls: 'x-html-editor-tip',
                   text:'右对齐'
                },
                insertunorderedlist:{
                   title:'Bullet List',
                   cls: 'x-html-editor-tip',
                   text:'项目符号'
                },
                insertorderedlist:{
                   title:'Numbered List',
                   cls: 'x-html-editor-tip',
                   text:'数字编号'
                },
                sourceedit:{
                   title:'Source Edit',
                    cls: 'x-html-editor-tip', 
                   text:'切换源代码编辑模式'  
                }
         }
         }
      ]  });

 

下面是acion中上传图片的实现,获取客户端图片的路径上传到工程中的upload文件夹中

// 上传图片
 public ActionForward uploadPic(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response) throws Exception{
          request.setCharacterEncoding("utf-8");
          response.setCharacterEncoding("utf-8");
          try {
               SmartUpload mySmartUpload = new SmartUpload();
               mySmartUpload.initialize(this.getServlet().getServletConfig(), request, response);
               mySmartUpload.upload();
               String separator = System.getProperty("file.separator"); // 系统路径分隔符
               String dir = mySmartUpload.getRequest().getRealPath("/") + separator;  // 绝对地址目录             
               for (int i = 0; i < mySmartUpload.getFiles().getCount(); i++) {
                     com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(i);
                    if (!myFile.isMissing()) {
                      String name = myFile.getFileName();  
                      String suffix = name.substring(name.lastIndexOf(".")); // 后缀名
                      name = QUtil.getTimeStr2() + suffix;// 给即将保存在服务器的文件赋予新的文件名
                      String fileName = dir + "upload" + separator + name; // 存储在服务器上的文件名(包括路径)
                      myFile.saveAs(fileName, mySmartUpload.SAVE_PHYSICAL);
                      // 获取图片的高度和宽度
                     BufferedImage img = ImageIO.read(new File(fileName));
                     int width = img.getWidth();
                     int height = img.getHeight();
                     if(width > 600){
                        height = ((Double)(height*600.0/width)).intValue();
                        width = 600;
                    }
                   String str = "{'success':true,'pic':'upload/"+name+"','width':'"+width+"','height':'"+height+"'}";
                   response.getWriter().print(str);
          }
      }
  } catch (Exception ex) {
   ex.printStackTrace();
   response.getWriter().print("{success:false}");
  }
  return null;
 }

  • 1
    点赞
  • 2
    评论
  • 0
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页

打赏作者

xfdyh

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值