百度編輯器umeditor使用總結

       百度編輯器是一個功能很全、很強大。
javascript

百度單張圖片上傳只能存儲在項目下面,而不能獨立自定義存儲位置,所以重寫上傳代碼php

百度文章中的圖片是經過base64實現的,直接存儲在數據庫中java

tomcat經過虛擬路徑實現將靜態資源從項目中獨立出來,避免更新項目解壓war後文件丟失數據庫


  


 




umeditor 配置都是在umeditor.config.jsapache

        //圖片上傳配置區
        ,imageUrl:URL+"jsp/imageUp.jsp"             //圖片上傳提交地址
        ,imagePath:URL + "jsp/"                     //圖片修正地址,引用了fixedImagePath,若有特殊需求,可自行配置
        ,imageFieldName:"upfile"                   //圖片數據的key,若此處修改,須要在後臺對應文件修改對應參數
json

定義文件位置tomcat

 

     window.UMEDITOR_CONFIG['imagePath'] = "/upload";

 

如何生成umeditor實例app

 

	 var um = UM.getEditor('myEditor');
	 
	 um.addListener('blur',function(){
		 var editorContent = UM.getEditor('myEditor').getContent();
		
		 if(editorContent != ""){
			 editorContent = filterHtml(editorContent);
			 $("#myEditorContent").val(escape(editorContent));
		 }
	 });


     文章內容含有圖片時,百度編輯器經過對圖片進行base64編碼,而後跟隨文章內容一塊兒保存在數據庫中。dom

 




如果經過圖片上傳按鈕插件,支持,php,asp,jsp接收,這樣主要講jsp,返回經過jsonp方式回調方法。image.js進行圖片的上傳和回調插入文章內容中jsp

 

    request.setCharacterEncoding("utf-8");
	response.setCharacterEncoding("utf-8");
    Uploader up = new Uploader(request);
    up.setSavePath("upload");
    String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
    up.setAllowFiles(fileType);
    up.setMaxSize(10000); //單位KB
    up.upload();

    String callback = request.getParameter("callback");

    String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize() +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";

    result = result.replaceAll( "\\\\", "\\\\" );

    if( callback == null ){
        response.getWriter().print( result );
    }else{
        response.getWriter().print("<script>"+ callback +"(" + result + ")</script>");
    }


接收圖片並保存到的代碼是

 

 

package com.baidu.ueditor.um;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.FileUploadBase.InvalidContentTypeException;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.util.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import com.moral.util.Common;
import com.moral.util.Constants;


import sun.misc.BASE64Decoder;
import javax.servlet.http.HttpServletRequest;
/**
 * UEditor文件上傳輔助類
 * 實現支持獨立定義上傳文件的路徑
 *
 */
public class Uploader {
	// 輸出文件地址
	private String url = "";
	
	// 上傳文件名
	private String fileName = "";
	
	// 狀態
	private String state = "";
	
	// 文件類型
	private String type = "";
	
	// 原始文件名
	private String originalName = "";
	
	// 文件大小
	private long size = 0;
	
	/*是否指定而外的絕對路徑*/
	private String physicalPath = Constants.Html.EDITOR_UPLOAD_PATH;

	private HttpServletRequest request = null;
	
	private String title = "";

	//百度插件默認的圖片在項目中保存路徑
	private String savePath = "upload";
	
	/*自定義的獨立的存儲路徑,目的是在從新發布後仍然保存有這些圖片,避免文件丟失*/
	private String aliasPath = "";
	
	// 文件容許格式
	private String[] allowFiles = { ".rar", ".doc", ".docx", ".zip", ".pdf",".txt", ".swf", ".wmv", ".gif", ".png", ".jpg", ".jpeg", ".bmp" };
	// 文件大小限制,單位KB
	private int maxSize = 10000;
	
	private HashMap<String, String> errorInfo = new HashMap<String, String>();

	public Uploader(HttpServletRequest request) {
		this.request = request;
		HashMap<String, String> tmp = this.errorInfo;
		tmp.put("SUCCESS", "SUCCESS"); //默認成功
		tmp.put("NOFILE", "未包含文件上傳域");
		tmp.put("TYPE", "不容許的文件格式");
		tmp.put("SIZE", "文件大小超出限制");
		tmp.put("ENTYPE", "請求類型ENTYPE錯誤");
		tmp.put("REQUEST", "上傳請求異常");
		tmp.put("IO", "IO異常");
		tmp.put("DIR", "目錄建立失敗");
		tmp.put("UNKNOWN", "未知錯誤");
		
	}

	public void upload() throws Exception {
		boolean isMultipart = ServletFileUpload.isMultipartContent(this.request);
		if (!isMultipart) {
			this.state = this.errorInfo.get("NOFILE");
			return;
		}
		DiskFileItemFactory dff = new DiskFileItemFactory();
		String savePath = this.getFolder(this.savePath);
		dff.setRepository(new File(savePath));
		try {
			ServletFileUpload sfu = new ServletFileUpload(dff);
			sfu.setSizeMax(this.maxSize * 1024);
			sfu.setHeaderEncoding("utf-8");
			FileItemIterator fii = sfu.getItemIterator(this.request);
			while (fii.hasNext()) {
				FileItemStream fis = fii.next();
				if (!fis.isFormField()) {
					this.originalName = fis.getName().substring(fis.getName().lastIndexOf(System.getProperty("file.separator")) + 1);
					if (!this.checkFileType(this.originalName)) {
						this.state = this.errorInfo.get("TYPE");
						continue;
					}
					this.fileName = this.getName(this.originalName);
					this.type = this.getFileExt(this.fileName);
					this.url = savePath + "/" + this.fileName;
					
					BufferedInputStream in = new BufferedInputStream(fis.openStream());
					File file = new File(this.getPhysicalPath(this.url));
					FileOutputStream out = new FileOutputStream( file );
					BufferedOutputStream output = new BufferedOutputStream(out);
					Streams.copy(in, output, true);
					
					/*複製文件到指定目錄下*/
					Common.copyFile(this.getPhysicalPath(this.url), this.aliasPath + "/" + this.fileName, true);

					this.state=this.errorInfo.get("SUCCESS");
					this.size = file.length();
					//UE中只會處理單張上傳,完成後即退出
					break;
				} else {
					String fname = fis.getFieldName();
					//只處理title,其他表單請自行處理
					if(!fname.equals("pictitle")){
						continue;
					}
                    BufferedInputStream in = new BufferedInputStream(fis.openStream());
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuffer result = new StringBuffer();  
                    while (reader.ready()) {  
                        result.append((char)reader.read());  
                    }
                    this.title = new String(result.toString().getBytes(),"utf-8");
                    reader.close();  
                    
				}
			}
		} catch (SizeLimitExceededException e) {
			this.state = this.errorInfo.get("SIZE");
		} catch (InvalidContentTypeException e) {
			this.state = this.errorInfo.get("ENTYPE");
		} catch (FileUploadException e) {
			this.state = this.errorInfo.get("REQUEST");
		} catch (Exception e) {
			this.state = this.errorInfo.get("UNKNOWN");
		}
	}
	
	/**
	 * 接受並保存以base64格式上傳的文件
	 * @param fieldName
	 */
	public void uploadBase64(String fieldName){
		String savePath = this.getFolder(this.savePath);
		String base64Data = this.request.getParameter(fieldName);
		this.fileName = this.getName("test.png");
		this.url = savePath + "/" + this.fileName;
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			File outFile = new File(this.getPhysicalPath(this.url));
			OutputStream ro = new FileOutputStream(outFile);
			byte[] b = decoder.decodeBuffer(base64Data);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {
					b[i] += 256;
				}
			}
			ro.write(b);
			ro.flush();
			ro.close();
			this.state=this.errorInfo.get("SUCCESS");
		} catch (Exception e) {
			this.state = this.errorInfo.get("IO");
		}
	}

	/**
	 * 文件類型判斷
	 * 
	 * @param fileName
	 * @return
	 */
	private boolean checkFileType(String fileName) {
		Iterator<String> type = Arrays.asList(this.allowFiles).iterator();
		while (type.hasNext()) {
			String ext = type.next();
			if (fileName.toLowerCase().endsWith(ext)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 獲取文件擴展名
	 * 
	 * @return string
	 */
	private String getFileExt(String fileName) {
		return fileName.substring(fileName.lastIndexOf("."));
	}

	/**
	 * 依據原始文件名生成新文件名
	 * @return
	 */
	private String getName(String fileName) {
		Random random = new Random();
		return this.fileName = "" + random.nextInt(10000)
				+ System.currentTimeMillis() + this.getFileExt(fileName);
	}

	/**
	 * 根據字符串建立本地目錄 並按照日期創建子目錄返回
	 * @param path 
	 * @return 
	 */
	private String getFolder(String path) {
		SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
		path += "/" + formater.format(new Date());
				
		System.out.println(this.getPhysicalPath(path));
		File dir = new File(this.getPhysicalPath(path));
		if (!dir.exists()) {
			try {
				dir.mkdirs();
			} catch (Exception e) {
				this.state = this.errorInfo.get("DIR");
				return "";
			}
		}
		
		this.aliasPath = this.physicalPath + "/" + path;
		
		System.out.println("aliasPath="+aliasPath);
		
		File aliasDir = new File(this.aliasPath);
		
		if(!aliasDir.exists()){
			try {
				aliasDir.mkdirs();
			} catch (Exception e) {
				e.printStackTrace();
			}			
		}
		
		return path;
	}

	/**
	 * 根據傳入的虛擬路徑獲取物理路徑
	 * 
	 * @param path
	 * @return
	 */
	private String getPhysicalPath(String path) {
		String realPath = "";

		String servletPath = this.request.getServletPath();
		realPath = this.request.getSession().getServletContext()
				.getRealPath(servletPath);			
		return new File(realPath).getParent() +"/" +path;
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

	public void setAllowFiles(String[] allowFiles) {
		this.allowFiles = allowFiles;
	}

	public void setMaxSize(int size) {
		this.maxSize = size;
	}

	public long getSize() {
		return this.size;
	}

	public String getUrl() {
		return this.url;
	}

	public String getFileName() {
		return this.fileName;
	}

	public String getState() {
		return this.state;
	}
	
	public String getTitle() {
		return this.title;
	}

	public String getType() {
		return this.type;
	}

	public String getOriginalName() {
		return this.originalName;
	}

	public String getPhysicalPath() {
		return physicalPath;
	}

	public void setPhysicalPath(String physicalPath) {
		this.physicalPath = physicalPath;
	}
}
相關文章
相關標籤/搜索