그림 삽입 기능 을 지원 하기 위해 html editor 확장 (종합)

20091 단어 editor
ExtJS html Editor 를 확장 하고 네트워크 그림 삽입, 로 컬 업로드 기능 을 지원 하 며 그림 표시 의 너비 와 높이 를 설정 할 수 있 습 니 다.
 
사용자 정의 확장 js
/**
 *   ExtJS htmlEditor  ,        、        
 * 
 * @author hzp
 */


Ext.namespace('Ext.ux','Ext.ux.plugins');  


Ext.ux.plugins.ImageDialog=function(config){
	config=config||{};  
	  
    Ext.apply(this,config);  
    var htmlEditorObj;
    this.init=function(htmlEditor) {  
        this.editor=htmlEditor;  
        htmlEditorObj=htmlEditor;
        this.editor.on('render',onRender,this);  
    };  
    
    function onRender(){  
        if( ! Ext.isSafari){  
            this.editor.tb.add({  
                itemId : 'htmlEditorImage',  
                cls : 'x-btn-icon x-edit-insertimage',  
                enableToggle : false,  
                scope : this,  
                handler : function(){  
                    this.imageWin();  
                },  
                clickEvent : 'mousedown',  
                tooltip : config.buttonTip ||   
                {  
                    title : '    ',  
                    text : '        ',  
                    cls : 'x-html-editor-tip'  
                },  
                tabIndex :- 1  
            });  
        }  
    }  
    
    var win;
    //       
    this.imageWin=function(){
    	win=new Ext.Window({
    		title:'    ',
    		width:400,
    		height:260,
    		resizable:false,
    		closeAction:'hide',
    		autoDestroy:false,
    		items:[{
    			xtype:'tabpanel',
    			anchor:'100%',
    			border: false,
    			activeTab: 0,
    			items:[
    			    //    
    			    webImg,
    			    //    
    			    uploadImage
    			]
    		}]
    	});
    	win.show()
    }
    
    //       
    var webImg=new Ext.form.FormPanel({
    	title:'    ',
    	anchor:'100%',
    	//height:200,
    	autoHeight:true,
    	labelWidth: 80,
    	labelAlign: 'right',
		border: false,
		autoDestroy:false,
		bodyStyle : 'padding-top:30px;',
    	items:[{
    		xtype:'textfield',
    		id:'wimgWidth',
			fieldLabel:'    ',
			name:'width',
			anchor:'90%'
    	},{
    		xtype:'textfield',
    		id:'wimgHeight',
			fieldLabel:'    ',
			name:'height',
			anchor:'90%'
    	},{
    		xtype:'textfield',
    		id:'wimgUrl',
			fieldLabel:'    ',
			anchor:'90%',
			emptyText:'http://',
			allowBlank:false,
			blankText:'        '
    	}],
    	buttons:[{
    		text:'  ',
    		handler:function(){
    			if(webImg.form.isValid()){
    				//        
    				var img="<img src='"+Ext.getCmp('wimgUrl').getValue()+"'";
    				//     
    				if(""!=Ext.getCmp('wimgHeight').getValue()){
    					img+= " height="+Ext.getCmp('wimgHeight').getValue();
    				}
    				//     
    				if(""!=Ext.getCmp('wimgWidth').getValue()){
    					img+= " width="+Ext.getCmp('wimgWidth').getValue()
    				}
    				img+= " />";
    				//    
    				htmlEditorObj.insertAtCursor(img);
    			}
    		}
    	},{
    		text:'  ',
    		handler:function(){ 
    			Ext.getCmp('wimgUrl').reset();
    			Ext.getCmp('wimgHeight').reset();
    			Ext.getCmp('wimgWidth').reset();
    			win.hide();	
    		}
    	}]
    });
    
    //       
    var uploadImage=new Ext.form.FormPanel({
    	title:'    ',
    	anchor:'100%',
    	//height:200,
    	autoHeight:true,
    	labelWidth: 80,
    	labelAlign: 'right',
		border: false,
		autoDestroy:false,
		bodyStyle : 'padding-top:30px;',
    	items:[{
    		xtype:'textfield',
    		id:'imgWidth',
			fieldLabel:'    ',
			name:'width',
			anchor:'90%'
    	},{
    		xtype:'textfield',
    		id:'imgHeight',
			fieldLabel:'    ',
			name:'height',
			anchor:'90%'
    	},{
    		xtype:'textfield',
    		id:'imgUrl',
			fieldLabel:'    ',
			name:'height',
			anchor:'90%',
			readOnly:true,
			allowBlank:false,
			blankText:'            ',
			listeners:{
				focus:function(obj){
					upload(obj);
				}
			}
    	}],
    	buttons:[{
    		text:'  ',
    		handler:function(){
    			//         
				var img="<img src='"+Ext.getCmp('imgUrl').getValue()+"'";
				//     
				if(""!=Ext.getCmp('imgHeight').getValue()){
					img+= " height="+Ext.getCmp('imgHeight').getValue();
				}
				//     
				if(""!=Ext.getCmp('imgWidth').getValue()){
					img+= " width="+Ext.getCmp('imgWidth').getValue()
				}
				img+= " />";
    			//    
    			htmlEditorObj.insertAtCursor(img);
    		}
    	},{
    		text:'  ',
    		handler:function(){  
    			Ext.getCmp('imgUrl').reset();
    			Ext.getCmp('imgHeight').reset();
    			Ext.getCmp('imgWidth').reset();
    			win.hide();	
    		}
    	}]
	});
    
    function upload(obj) {
    	var dialog = new Ext.ux.UploadDialog.Dialog({  
		    title:config.title || '    ',  
		    url: config.url || '',  
		    post_var_name: config.post_var_name || 'file',
		    reset_on_hide: config.reset_on_hide || false,  
		    modal: config.modal || true,
		    draggable: config.draggable || true,
		    proxyDrag: config.proxyDrag || true,   
	        resizable: config.resizable || true,   
	        constraintoviewport: true,  
		    permitted_extensions: config.permitted_extensions || ['JPG','jpg','GIF','gif','PNG','png'],  
		    allow_close_on_upload: config.allow_close_on_upload || false,  
		    upload_autostart: config.upload_autostart || true //      
		}); 
		dialog.show();
		//         
		dialog.on('uploadsuccess',function(dialog, filename, resp_data, record){
	    	//               imgUrl  
	    	Ext.getCmp('imgUrl').setValue(resp_data.data.msg);
	    	dialog.hide();
		});
    }
    
}


 
 
참조 페이지
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<link rel="stylesheet" type="text/css" href="extjs2.3/resources/css/ext-all.css" />
		<script type="text/javascript" src="extjs2.3/adapter/ext/ext-base.js"></script>
		<script type="text/javascript" src="extjs2.3/ext-all.js"></script>
		
		<script type="text/javascript" src="extjs2.3/ux/upload/js/Ext.ux.UploadDialog.js" ></script>  
		<script type="text/javascript" src="extjs2.3/ux/upload/js/Ext.ux.UploadDialog.packed.js"></script>
    	<link rel="stylesheet" type="text/css" href="extjs2.3/ux/upload/css/Ext.ux.UploadDialog.css"/>   
		<script type="text/javascript" src="customer.js" ></script>
		<script type="text/javascript" src="Ext.ux.UploadDialog.zh-cn.js" ></script>
			
		<script type="text/javascript">

			Ext.onReady(function(){
				
				Ext.QuickTips.init();  
				  
			    new Ext.form.HtmlEditor({  
			        renderTo: 'form',  
			        id:'content',
			        width: 650,  
			        height: 350,  
			        plugins: new Ext.ux.plugins.ImageDialog
({
			        		    url: '/ExtjsTest/upload.action',  
			        		    post_var_name:'imageUpload'
			                })  
			    });  
			});
			
		</script>
	
	</head>

	<body>
		<div id="form"></div>
	</body>
</html>

 
 
업로드 서버 처리
package com.hzp;

import java.io.File;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport{

	
	//    
	private File imageUpload;
	private String imageUploadContentType;
	private String imageUploadFileName;
	

	//    ,     imageUrl         
	public String uploadImage()throws Exception{
		HttpServletResponse response=ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter pw=response.getWriter();
		String result="{success:false}";
		try {
			//           ,    
			if (null != imageUpload) {
				String path = FileSystem.uploadFile(this.imageUpload,getExtention(imageUploadFileName));
				//     ,     
				if (null != path) {
					String img=FileSystem.getFileSystemFileRootPath()+path;
					result="{success:true,data:{msg:'"+img+"'}}";
				}
			}
			pw.print(result);
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			pw.print(result);
			return null;
		}finally{
			pw.flush();
			pw.close();
		}
	}
	
	//          : .txt
	private String getExtention(String fileName) {
         int pos = fileName.lastIndexOf( "." );
         return fileName.substring(pos).toString();
    }
	
	public File getImageUpload() {
		return imageUpload;
	}

	public void setImageUpload(File imageUpload) {
		this.imageUpload = imageUpload;
	}

	public String getImageUploadContentType() {
		return imageUploadContentType;
	}

	public void setImageUploadContentType(String imageUploadContentType) {
		this.imageUploadContentType = imageUploadContentType;
	}

	public String getImageUploadFileName() {
		return imageUploadFileName;
	}

	public void setImageUploadFileName(String imageUploadFileName) {
		this.imageUploadFileName = imageUploadFileName;
	}
	
	
}

 
 
파일 서버 통신 도구 클래스
package com.hzp;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import javax.servlet.http.HttpServletResponse;

import com.sun.xml.internal.ws.util.StringUtils;

/**
 *                      ,     、     
 * 
 * @author hzp
 * 
 */
public class FileSystem {

	//              


	private static InputStream in = FileSystem.class.getClassLoader()
			.getResourceAsStream("fileSystem.properties");
	private static Properties p = new Properties();

	//     url  (ip   )
	private static String path = "http://localhost:"
			+ ServletActionContext.getRequest().getLocalPort();

	//               
	public static String getFileSystemFileRootPath() throws Exception {
		p.load(in);
		String root = path + p.getProperty("file_root_path");
		return root;
	}

	//            servlet   


	public static String getFileSystemUploadServletPath() throws Exception {
		p.load(in);
		String root = path + p.getProperty("upload_servlet");
		return root;
	}

	//            servlet   


	public static String getFileSystemDownloadServletPath() throws Exception {
		p.load(in);
		String root = path + p.getProperty("download_servlet");
		return root;
	}

	/**
	 *                
	 * 
	 * @param upload
	 *                  
	 * @param fileType
	 *                ,  .txt .jpg
	 * @return                 ,   null
	 * @throws Exception
	 */
	public static String uploadFile(File upload, String fileType)
			throws Exception {
		InputStream is = null;
		OutputStream os = null;
		HttpURLConnection conn = null;
		String filePath = null;
		try {
			//          ,            
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String savePath = "/" + sdf.format(new Date());

			//         
			String newFileName = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss")
					.format(new Date()) + fileType;

			//            


			filePath = savePath + "/" + newFileName;

			String url = getFileSystemUploadServletPath() + "?savePath="
					+ savePath + "&newFileName=" + newFileName;

			// *********        ,     ********//
			URL u = new URL(url);
			conn = (HttpURLConnection) u.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setRequestMethod("POST");
			conn.setConnectTimeout(10000);
			conn.setUseCaches(false);
			conn.setInstanceFollowRedirects(true);
			conn.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			conn.setChunkedStreamingMode(64);
			conn.connect();
			os = conn.getOutputStream();
			is = new BufferedInputStream(new FileInputStream(upload));
			//     
			byte[] buffer = new byte[8192];
			int length = 0;

			while ((length = is.read(buffer)) > 0) {
				os.write(buffer, 0, length);
			}
			os.flush();
			conn.getInputStream();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			//     
			if (null != is) {
				is.close();
			}
			if (null != os) {
				os.close();
			}
			if (null != conn) {
				conn.disconnect();
			}
		}
		//                  ,          
		if (conn.getResponseCode() == HttpServletResponse.SC_OK) {
			return filePath;
		} else {
			return null;
		}
	}

	/**
	 *                
	 * 
	 * @param bytes
	 *                       

	 * 
	 * @param fileType
	 *                ,  .txt .jpg
	 * @return                 ,   null
	 * @throws Exception
	 */
	public static String uploadFile(byte[] bytes, String fileType)
			throws Exception {
		OutputStream os = null;
		HttpURLConnection conn = null;
		String filePath = null;
		try {
			//          ,            
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String savePath = "/" + sdf.format(new Date());

			//         
			String newFileName = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss")
					.format(new Date()) + fileType;

			//            


			filePath = savePath + "/" + newFileName;

			String url = getFileSystemUploadServletPath() + "?savePath="
					+ savePath + "&newFileName=" + newFileName;

			// *********        ,     ********//
			URL u = new URL(url);
			conn = (HttpURLConnection) u.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setRequestMethod("POST");
			conn.setConnectTimeout(10000);
			conn.setUseCaches(false);
			conn.setInstanceFollowRedirects(true);
			conn.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			conn.setChunkedStreamingMode(64);
			conn.connect();
			os = conn.getOutputStream();
			os.write(bytes);
			os.flush();
			conn.getInputStream();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			//     
			if (null != os) {
				os.close();
			}
			if (null != conn) {
				conn.disconnect();
			}
		}
		//                  ,          
		if (conn.getResponseCode() == HttpServletResponse.SC_OK) {
			return filePath;
		} else {
			return null;
		}
	}

	/**
	 *     
	 * 
	 * @param filePath
	 *                     

	 * 
	 * 
	 * @return
	 * @throws Exception
	 */
	public static InputStream downloadFile(String filePath) throws Exception {

		HttpURLConnection conn = null;

		String url = getFileSystemDownloadServletPath() + "?filePath="
				+ filePath;

		// *********        ********//
		URL u = new URL(url);
		conn = (HttpURLConnection) u.openConnection();
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setUseCaches(false);
		conn.setConnectTimeout(10000);
		conn.setRequestMethod("POST");
		conn.connect();
		BufferedInputStream is = new BufferedInputStream(conn.getInputStream());

		//                  ,       


		if (conn.getResponseCode() == HttpServletResponse.SC_OK) {
			return is;
		} else {
			return null;
		}
	}

	/**
	 *       
	 * 
	 * <p>
	 *            ,          :“.txt”、“.jpg” ,             。<br/>
	 *   :         ,         ;       ,   <code>null</code>。

	 * </p>
	 * 
	 * @param fileName
	 *               

	 * 
	 * @return <code>postfix</code>     
	 */
	public static String getFilePostfix(String fileName) {
		String postfix = null;
		if (fileName==null || fileName=="") {
			return postfix;
		}
		fileName = fileName.trim();
		int pos = fileName.lastIndexOf(".");
		if (pos == -1) {
			postfix = "";
			return "";
		} else {
			postfix = fileName.substring(pos).toString().toLowerCase();
		}
		return postfix;
	}
}

 
 
 

좋은 웹페이지 즐겨찾기