百度编辑器是一个功能很全、很强大。

百度单张图片上传只能存储在项目下面,而不能独立自定义存储位置,因此重写上传代码

百度文章中的图片是通过base64实现的,直接存储在数据库中

tomcat通过虚拟路径实现将静态资源从项目中独立出来,避免更新项目解压war后文件丢失

umeditor 配置都是在umeditor.config.js

//图片上传配置区
        ,imageUrl:URL+"jsp/imageUp.jsp"             //图片上传提交地址
        ,imagePath:URL + "jsp/"                     //图片修正地址,引用了fixedImagePath,如有特殊需求,可自行配置
        ,imageFieldName:"upfile"                   //图片数据的key,若此处修改,需要在后台对应文件修改对应参数

定义文件位置

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

如何生成umeditor实例

	 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编码,然后跟随文章内容一起保存在数据库中。

若是通过图片上传按钮插件,支持,php,asp,jsp接收,这样主要讲jsp,返回通过jsonp方式回调方法。image.js进行图片的上传和回调插入文章内容中

    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;
}
}

百度编辑器umeditor使用总结的更多相关文章

  1. yii2解决百度编辑器umeditor图片上传问题

    作者:白狼 出处:http://www.manks.top/article/yii2_umeditor_upload本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原 ...

  2. yii2整合百度编辑器umeditor

    作者:白狼 出处:www.manks.top/article/yii2_umeditor 本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责 ...

  3. 一步步开发自己的博客 .NET版(4、文章发布功能)百度编辑器

    前言 这次开发的博客主要功能或特点: 第一:可以兼容各终端,特别是手机端. 第二:到时会用到大量html5,炫啊. 第三:导入博客园的精华文章,并做分类.(不要封我) 第四:做个插件,任何网站上的技术 ...

  4. 封装Web Uploader 上传插件、My97DatePicker、百度 编辑器 的使用 (ASP.NET MVC)

    Web Uploader: WebUploader是由Baidu WebFE(FEX)团队开发的一个简单的以HTML5为主,FLASH为辅的现代文件上传组件.在现代的浏览器里面能充分发挥HTML5的优 ...

  5. yii2-Ueditor百度编辑器

    今天在网上看了下有关图片上传的教程,历经挫折才调试好,现在把相关代码及其说明贴出来,以供初次使用的朋友们参考. 资源下载 yii2.0-ueditor下载路径: https://link.jiansh ...

  6. 关于百度编辑器UEditor的一点说明

    大家在使用的时候要特别注意editor_config.js中的“URL”这个参数 我的理解:1.这个参数是editor整个结构的总路径          2.首先要把这个路径配置好了.才能正常的显示, ...

  7. 百度编辑器ueditor插入表格没有边框颜色的解决方法

    附:从word excel 中 复制的表格提交后无边框,参考这个同学的,写的很详细:   http://blog.csdn.net/lovelyelfpop/article/details/51678 ...

  8. 百度编辑器UEditor的使用方法

    百度编辑器具有丰富文本编辑功能,且开源免费,其使用方法如下: 1.在官网上下载对应的Uditor压缩包:http://ueditor.baidu.com/website/download.html 2 ...

  9. 百度编辑器ueditor插入表格没有边框,没有颜色的解决方法 2015-01-06 09:24 98人阅读 评论(0) 收藏

    百度富文本编辑器..很强大.. - - ,不过有些BUG..真的很无解.. 最近用这个,发现上传的表格全部没有表框.. 解决办法如下: 转载的.. 百度编辑器ueditor插入一个表格后,在编辑过程中 ...

随机推荐

  1. BZOJ_1610_[Usaco2008_Feb]_Line连线游戏_(计算几何基础+暴力)

    描述 http://www.lydsy.com/JudgeOnline/problem.php?id=1610 给出n个点,问两两确定的直线中,斜率不同的共有多少条. 分析 暴力枚举直线,算出来斜率放 ...

  2. POJ_3061_Subsequence_(尺取法)

    描述 http://poj.org/problem?id=3061 给定长度为n的数列整数以及整数S.求出总和不小于S的连续子序列的长度的最小值,如果解不存在输出0. Subsequence Time ...

  3. javascript中的 && 与 || 的运用

    a && b : 将a, b转换为Boolean类型, 再执行逻辑与, true返回b, false返回a a || b : 将a, b转换为Boolean类型, 再执行逻辑或, tr ...

  4. c#集合类的线程安全

    即位于System.Collections命名空间下的集合,如Hashtable,ArrayList,Stack,Queue等.其均提供了线程同步的一个实现 集合线程同步的问题 public clas ...

  5. Api项目压力测试知识荟萃

    并发用户.在线用户和注册用户以及彼此之间的换算方法(估算模型).系统的最大并发用户数根据注册用户数来获得,换算方法一般是注册总人数的5%-20%之间:系统的并发数根据在线人数来获得,换算方法一般是在3 ...

  6. 最常用的Java库一览

    本文由 ImportNew - 邢 敏 翻译自 programcreek.欢迎加入翻译小组.转载请见文末要求. 写在前面: 1) 本文列出的名单是根据我自己的调查,并结合个人的经验.有可能是它们不恰恰 ...

  7. Storm与Hadoop的角色和组件比较

    Storm与Hadoop的角色和组件比较 Storm 集群和 Hadoop 集群表面上看很类似.但是 Hadoop 上运行的是 MapReduce 作业,而在 Storm 上运行的是拓扑 Topolo ...

  8. canvas createRadialGradient 用法

    径向渐变,就是环形的渐变了,由圆心(或者是较小的同心圆)开始向外扩散渐变的效果,听着有些抽象,往下看图一下子就明白了.线性渐变指定了起点和终点,径向渐变则指定了开始的结束园的圆心和半径.这里使用cre ...

  9. java常见算法

    1.冒泡排序 public int[] bubbleSort(int arr){ int temp; boolean isOk; for(int i = 0; i < arr.length; i ...

  10. 1、IIS常见的的问难及解决方法

    配置IIS 7.5 出现的问题及解决办法: 1.问题:  CS0016: 未能写入输出文件“c:\Windows\Microsoft.NET\Framework64\v4.0.30319\Tempor ...