django 是基于 python 的一个很好的web开发框架。ueditor 是百度开源的一个富文本编辑器。有很好的用户体验,很适合中国人使用的一个编辑器。

在使用ueditor 之前,我集成过 fckeditor , ckeditor 。基本没什么难度。但功能没有ueditor 强大。因此产生了用django 集成 ueditor 的想法。

查看了百度官方的文档以及例子,发现只有 java,php,.net 版本的例子提供,而并没有python,或django的例子。所以就只能自己造轮子了。富文本编辑器,只是个JS框架,与后台基本没有关系。后台只是响应 HTTP 请求,做出处理,并返回结果就好。所以用DJANGO来处理,应该也很容易,开工吧。

下载百度ueditor 
这个就不必多说了,地球人都知道,百度一下就知道了。要注意的是,我下载的是 java utf-8 版本的,因为没有 django 版本的,所以你随便下载一个适合自己的 完整版本就可以了。

做一个html模板页面,在 head 部分,包含以下内容(路径要改成适合你自己的):

 程序代码

<script type="text/javascript" charset="utf-8">
        window.UEDITOR_HOME_URL = "/static/js/ueditor/";
    </script> 
    <script type="text/javascript" charset="utf-8" src="/static/js/ueditor/editor_config.js"></script>
    <script type="text/javascript" charset="utf-8" src="/static/js/ueditor/editor_all_min.js"></script>
    <link rel="stylesheet" type="text/css" href="/static/js/ueditor/themes/default/ueditor.css"/>    

模板的正文可以是如下内容,在<body>与</body>之间:

 程序代码

<textarea id="content" name="content" style="width:575px;line-height:18px;"></textarea> 

在html模板的结尾,在</body>之前,加上如下代码:

 程序代码

<script>
    var ue=new UE.ui.Editor();
    ue.render('content');
</script>

到此,模板配置完毕。在django 工程的 urls.py 文件中配置一个url 路径,访问该模板页面,现在可以看到编辑器加载成功:

这是,点击上传图片图标,可以看到可以用本地上传,选择多个图片,但却无法上传,原因很简单,没有后台响应。所以需要些django后台来处理。
新建一个 app, 比如 Ueditor,看我的工程结构:

在里面建立一个 views.py 文件,代码如下:

 程序代码

#coding:utf-8
'''
Created on 2012-8-29
@author: yihaomen.com
'''
from XieYin import settings
from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
import Image
import os
import time
import urllib2
import uuid

def __myuploadfile(fileObj, source_pictitle, source_filename,fileorpic='pic'):
    """ 一个公用的上传文件的处理 """
    myresponse=""
    if fileObj:
        filename = fileObj.name.decode('utf-8', 'ignore')
        fileExt = filename.split('.')[1]
        file_name = str(uuid.uuid1())
        subfolder = time.strftime("%Y%m")
        if not os.path.exists(settings.MEDIA_ROOT[0] + subfolder):
            os.makedirs(settings.MEDIA_ROOT[0] + subfolder)
        path = str(subfolder + '/' + file_name + '.' + fileExt)
        
        if fileExt.lower() in ('jpg', 'jpeg', 'bmp', 'gif', 'png',"rar" ,"doc" ,"docx","zip","pdf","txt","swf","wmv"):
        
            phisypath = settings.MEDIA_ROOT[0] + path
            destination = open(phisypath, 'wb+')
            for chunk in fileObj.chunks():
                destination.write(chunk)            
            destination.close()
            
            if fileorpic=='pic':
                if fileExt.lower() in ('jpg', 'jpeg', 'bmp', 'gif', 'png'):
                    im = Image.open(phisypath)
                    im.thumbnail((720, 720))
                    im.save(phisypath)
                    
            real_url = '/static/upload/' + subfolder + '/' + file_name + '.' + fileExt      
            myresponse = "{'original':'%s','url':'%s','title':'%s','state':'%s'}" % (source_filename, real_url, source_pictitle, 'SUCCESS')
    return myresponse

@csrf_exempt
def ueditor_ImgUp(request): 
    """ 上传图片 """   
    fileObj = request.FILES.get('upfile', None)   
    source_pictitle = request.POST.get('pictitle','')
    source_filename = request.POST.get('fileName','')  
    response = HttpResponse()  
    myresponse = __myuploadfile(fileObj, source_pictitle, source_filename,'pic')
    response.write(myresponse)
    return response
   
    
@csrf_exempt
def ueditor_FileUp(request): 
    """ 上传文件 """   
    fileObj = request.FILES.get('upfile', None)   
    source_pictitle = request.POST.get('pictitle','')
    source_filename = request.POST.get('fileName','')    
    response = HttpResponse()  
    myresponse = __myuploadfile(fileObj, source_pictitle, source_filename,'file')
    response.write(myresponse)
    return response

@csrf_exempt 
def ueditor_ScrawUp(request):
    """ 涂鸦文件,处理 """
    pass

到目前为止,刚接触ueditor ,时间有限,我就做了上传文件和图片的。涂鸦,抓远程图片等,我在有时间的时候会补充出来。

在urls.py 中配置

 程序代码

url(r'^ueditor_imgup$','XieYin.app.Ueditor.views.ueditor_ImgUp'),
url(r'^ueditor_fileup$','XieYin.app.Ueditor.views.ueditor_FileUp'), 

修改百度ueditor 配置文件:editor_config.js

 程序代码

//,imageUrl:URL+"jsp/imageUp.jsp"  
  ,imageUrl:"/ueditor_imgup"
  //图片上传提交地址
,imagePath:""

//附件上传配置区
,fileUrl:"/ueditor_fileup"               //附件上传提交地址
,filePath:""

启动django程序
进入刚才的页面,选择上传图片.

到此,图片上传成功,其实文件也一样,只不过类型不同而已。

注意

程序确实实现了上传于ueditor 的继承。但还没有考虑到安全性,比如session的检查等。需要的,可以自己加上。

上一篇文章提到django与百度ueditor 结合实现文件上传,图片上传。但还有如下功能没实现:
1. 在线涂鸦后,图片的保存,并显示
2. 图片的在线管理,浏览(目录递归浏览)
3. 在线视频搜索
4. 远程抓图

在看测试代码之前,请注意在django程序的settings.py 中配置:

 程序代码

MEDIA_ROOT = os.path.join(os.path.dirname(__file__),'static/upload/').replace('\\','/'),

这是我的配置,你可以改成适合你的配置。

今天又抽了一个小时,参考了下java 的代码,将上面的四个功能也实现,有需要的朋友可以参考. 同样在前面文章的基础上,在views.py 里面添加代码:
在线涂鸦

 程序代码

@csrf_exempt 
def ueditor_ScrawUp(request):
    """ 涂鸦文件,处理 """
    print request
    param = request.POST.get("action",'')
    fileType = [".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"];
    
    if  param=='tmpImg':
        fileObj = request.FILES.get('upfile', None)   
        source_pictitle = request.POST.get('pictitle','')
        source_filename = request.POST.get('fileName','')  
        response = HttpResponse()  
        myresponse = __myuploadfile(fileObj, source_pictitle, source_filename,'pic')
        myresponsedict=dict(myresponse)
        url=myresponsedict.get('url','')
        response.write("<script>parent.ue_callback('%s','%s')</script>" %(url,'SUCCESS'))
        return response
    else:
        #========================base64上传的文件======================= 
        base64Data = request.POST.get('content','')
        subfolder = time.strftime("%Y%m")
        if not os.path.exists(settings.MEDIA_ROOT[0] + subfolder):
            os.makedirs(settings.MEDIA_ROOT[0] + subfolder)
        file_name = str(uuid.uuid1())
        path = str(subfolder + '/' + file_name + '.' + 'png')
        phisypath = settings.MEDIA_ROOT[0] + path        
        f=open(phisypath,'wb+')
        f.write(base64.decodestring(base64Data))
        f.close()
        response=HttpResponse()
        response.write("{'url':'%s',state:'%s'}" % ('/static/upload/' + subfolder + '/' + file_name + '.' + 'png','SUCCESS'));
        return response



图片的在线管理,浏览(目录递归浏览)

 程序代码

def listdir(path,filelist):
    """ 递归 得到所有图片文件信息 """
    phisypath = settings.MEDIA_ROOT[0]
    if os.path.isfile(path):
        return '[]' 
    allFiles=os.listdir(path)
    retlist=[]
    for cfile in allFiles:
        fileinfo={}
        filepath=(path+os.path.sep+cfile).replace("\\","/").replace('//','/')        
        
        if os.path.isdir(filepath):
            listdir(filepath,filelist)
        else:
            if cfile.endswith('.gif') or cfile.endswith('.png') or cfile.endswith('.jpg') or cfile.endswith('.bmp'):
                filelist.append(filepath.replace(phisypath,'/static/upload/').replace("//","/"))

@csrf_exempt
def ueditor_imageManager(request):
    """ 图片在线管理  """
    filelist=[]
    phisypath = settings.MEDIA_ROOT[0]
    listdir(phisypath,filelist)
    imgStr="ue_separate_ue".join(filelist)
    response=HttpResponse()
    response.write(imgStr)     
    return response


在线视频搜索

 程序代码

@csrf_exempt
def ueditor_getMovie(request):
    """ 获取视频数据的地址 """
    content ="";   
    searchkey = request.POST.get("searchKey");
    videotype = request.POST.get("videoType");
    try:        
        url = "http://api.tudou.com/v3/gw?method=item.search&appKey=myKey&format=json&kw="+ searchkey+"&pageNo=1&pageSize=20&channelId="+videotype+"&inDays=7&media=v&sort=s";
        content=urllib2.urlopen(url).read()
    except Exception,e:
        pass
    response=HttpResponse()  
    response.write(content);
    return response

远程抓图,将别人网站的图片保存到本地,并显示出来

 程序代码

@csrf_exempt 
def ueditor_getRemoteImage(request):
    print request
    """ 把远程的图抓到本地,爬图 """
    file_name = str(uuid.uuid1())
    subfolder = time.strftime("%Y%m")    
    if not os.path.exists(settings.MEDIA_ROOT[0] + subfolder):
        os.makedirs(settings.MEDIA_ROOT[0] + subfolder)    
    #====get request params=================================
    urls = str(request.POST.get("upfile"));
    urllist=urls.split("ue_separate_ue")
    outlist=[]
    #====request params end=================================    
    fileType = [".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"];    
    for url in urllist:
        fileExt=""
        for suffix in fileType:
            if url.endswith(suffix):
                fileExt=suffix
                break;
        if fileExt=='':
            continue
        else:
            path = str(subfolder + '/' + file_name + '.' + fileExt)
            phisypath = settings.MEDIA_ROOT[0] + path
            piccontent= urllib2.urlopen(url).read()
            picfile=open(phisypath,'wb')
            picfile.write(piccontent)
            picfile.close()
            outlist.append('/static/upload/' + subfolder + '/' + file_name + '.' + fileExt)
    outlist="ue_separate_ue".join(outlist)
    
    response=HttpResponse()
    myresponse="{'url':'%s','tip':'%s','srcUrl':'%s'}" % (outlist,'成功',urls)
    response.write(myresponse);
    return response

更新 urls.py

 程序代码

    url(r'^ueditor_imgup$','MyNet.app.Ueditor.views.ueditor_ImgUp'),
    url(r'^ueditor_fileup$','MyNet.app.Ueditor.views.ueditor_FileUp'),
    url(r'^ueditor_getRemoteImage$','MyNet.app.Ueditor.views.ueditor_getRemoteImage'),
    url(r'^ueditor_scrawlUp$','MyNet.app.Ueditor.views.ueditor_ScrawUp'),
    url(r'^ueditor_getMovie$','MyNet.app.Ueditor.views.ueditor_getMovie'),
    url(r'^ueditor_imageManager$','MyNet.app.Ueditor.views.ueditor_imageManager'),

更改ueditor config 配置文件

 程序代码

        ,imageUrl:"/ueditor_imgup"
        ,imagePath:""  
        //涂鸦图片配置区
        ,scrawlUrl:"/ueditor_scrawlUp" 
        ,scrawlPath:""

//附件上传配置区
        ,fileUrl:"/ueditor_fileup" 
        ,filePath:""

//远程抓取配置区
        ,catcherUrl:"/ueditor_getRemoteImage" 
        ,catcherPath:""

//图片在线管理配置区
        ,imageManagerUrl:"/ueditor_imageManager" 
        ,imageManagerPath:""

//屏幕截图配置区
        ,snapscreenHost: '127.0.0.1'
        ,snapscreenServerUrl: "/ueditor_imgup" 
        ,snapscreenPath: ""
        
        //word转存配置区
       
        ,wordImageUrl:"/ueditor_imgup"
        ,wordImagePath:""

//获取视频数据的地址
        ,getMovieUrl:"/ueditor_getMovie"

到此为止,这两篇文章将所有需要集成的都集成了。

django 与 百度 ueditor 富文本编辑器集成相关推荐

  1. java 百度副文本_spring boot 、springMVC环境集成百度ueditor富文本编辑器

    spring-boot-mvc-ueditor-qiniu spring boot .springMVC环境集成百度ueditor富文本编辑器,使用七牛云存储图片 依赖库版本: spring boot ...

  2. php引入百度Ueditor富文本编辑器

    php引入百度Ueditor富文本编辑器 文本编辑器插件内容丰富,比起传统的textarea标签输入要好用很多,看看如何在页面实现引入吧 1.下载适合的资源包(可以去官网下载适合的版本),我是php引 ...

  3. 百度UEditor富文本编辑器去除自动追加span标签

    #消息模板实时翻译 1.消息模板支持实时翻译,并且将消息模板中的主题.消息.短信.邮件修改为消息富文本编辑器,对主题和短信的富文本编辑器工具进行隐藏. 2.替换规则:    同步拼接编码和label, ...

  4. phpeditor编写php_PHP如何搭建百度Ueditor富文本编辑器

    本文为大家分享了PHP搭建百度Ueditor富文本编辑器的方法,供大家参考,具体内容如下 下载UEditor 将下载好的文件解压到thinkphp项目中,本文是解压到PUBLIC目录下并改文件夹名称为 ...

  5. ueditor html中使用方法,vue集成百度UEditor富文本编辑器使用教程

    在前端开发的项目中,难免会遇到需要在页面上集成一个富文本编辑器.那么,如果你有这个需求,希望可以帮助到你. vue是前端开发者所追捧的框架,简单易上手,但是基于vue的富文本编辑器大多数太过于精简.于 ...

  6. 解决百度ueditor富文本编辑器不能插入视频的问题/src掉链/src清空,不能显示视频

    如果你嫌弃自己配置比较麻烦,出现各种奇奇怪怪的问题你下载我  这个文件  加入到你的项中, 只  需要  修改 项目名称  就可以 运行  地址 https://download.csdn.net/d ...

  7. 【php】ThinkPHP搭建百度Ueditor富文本编辑器

    简介 UEditor是由百度web前端研发部开发所见即所得富文本web编辑器,具有轻量,可定制,注重用户体验等特点,开源基于MIT协议,允许自由使用和修改代码. 下载UEditor 官网下载:http ...

  8. 江湖CMS框架改成百度UEditor富文本编辑器

    下载UEedit到/public/ueditor下.ueditor1_4_3_3-utf8-php版 添加文章模版/h1sg/web/system/admin/view/article/article ...

  9. 百度Ueditor富文本编辑器修改上传图片的默认路径绝对能用,并且回显,并且超级简单,超级详情,有用点赞好评!

    最近做一个项目,项目做完了,再部署的时候,人家要求webapps不能存放图片什么的,因为如果变更,就图片什么就没了,好了现在开始修改. 当初做这个功能的时候,查了很多,感觉都是神仙,代码各种不全,完成 ...

最新文章

  1. java邮件接收代码,JavaMail入门第四篇 接收邮件(示例代码)
  2. 【Python-ML】SKlearn库特征抽取-PCA
  3. Oracle 外连接和 (+)号的用法
  4. Pixhawk(PX4)之驱动详解篇(0)_前期准备(招贤令)
  5. 为什么不要使用长事务
  6. 为什么知乎页面按Ctrl C 会自动粘贴一部份文字出来?
  7. 玩转git-flow工作流-分支解析
  8. mq集群要建传输队列吗_面试官:消息队列这些我必问!
  9. JavaSE——常用类库(String类)
  10. 递归算法,JavaScript实现
  11. javascript基础知识(16) 变量提升
  12. 无法安装 计算机缺失,还原安装程序Windows缺失的文件 - Windows Client | Microsoft Docs...
  13. 编程大讲坛 坛坛是佳酿--编程大讲坛:C语言核心开发技术从入门到精通
  14. Emmet的HTML语法(敲代码的快捷方式)
  15. 微软云服务器搭建,75分钟快速构建微软Server 2012私有云
  16. 全国地表径流量数据获取/植被类型数据/NPP数据/土壤侵蚀数据/土壤质地分类/降雨量栅格数据/太阳辐射量数据
  17. python什么表示空类型_在 Python 中 __________ 表示空类型。 (2.0分)_学小易找答案
  18. java 检测u盘_Java简单U盘检测程序
  19. 如何在 DAO 中找到个人自由并实现自我价值?
  20. Linux系统开启服务器BBR加速教程

热门文章

  1. 【Groovy】MOP 元对象协议与元编程 ( 使用 Groovy 元编程进行函数拦截 | 重写 MetaClass#invokeMethod 方法实现函数拦截 | 实现函数调用转发 )
  2. 【Android 逆向】整体加固脱壳 ( DEX 优化流程分析 | DexPrepare.cpp 中 dvmOptimizeDexFile() 方法分析 | /bin/dexopt 源码分析 )
  3. 【Windows 逆向】OD 调试器工具 ( OD 工具简介 | OD 工具与 CE 工具对比 )
  4. 【Android APT】编译时技术 ( ButterKnife 原理分析 )
  5. 【MATLAB】matlab 文档使用 ( 文档查询 | 文档层次 | 自带搜索工具 | 帮助命令 | 学习导引 )
  6. 【鸿蒙 HarmonyOS】UI 组件 ( 文本输入框 TextField 组件 )
  7. 【Android FFMPEG 开发】Android Studio 工程配置 FFMPEG ( 动态库打包 | 头文件与函数库拷贝 | CMake 脚本配置 )
  8. 图解反向代理和正向代理。
  9. hdu1247 Hat’s Words
  10. WIN server 2003 下无法安装adobe cs3 终极解决方法。