随笔 - 35,  文章 - 0,  评论 - 0,  阅读 - 12503

UEditor介绍

UEditor 是由百度「FEX前端研发团队」开发的所见即所得富文本web编辑器,具有轻量,可定制,注重用户体验等特点,开源基于MIT协议,允许自由使用和修改代码。、

首先下载插件
zh-cn.js这个是中文的一些文件
ueditor.all.js
ueditor.config.js

<script src="{{ buildStaticUrl('/plugins/ueditor/ueditor.config.js') }}"></script>
<script src="{{ buildStaticUrl('/plugins/ueditor/ueditor.all.min.js') }}"></script>
<script src="{{ buildStaticUrl('/plugins/ueditor/lang/zh-cn/zh-cn.js') }}"></script>

通过官方文档了解接口

//因为害怕作用域改变所以进行定义一个that
var that = this;
that.ue = UE.getEditor('editor', {
            //更改显示功能
            toolbars: [
                [ 'undo', 'redo', '|',
                   'bold', 'italic', 'underline', 'strikethrough', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall',  '|','rowspacingtop', 'rowspacingbottom', 'lineheight'],
                [ 'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
                   'directionalityltr', 'directionalityrtl', 'indent', '|',
                   'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
                'link', 'unlink'],
                [ 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
                    'insertimage', 'insertvideo', '|',
                    'horizontal', 'spechars','|','inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols' ]
            ],
            //启动自动保存
            enableAutoSave:true,
            //saveInterval是自动保存的时间,设置成很大也就是自动保存的时间久一点
            saveInterval:60000,
            //它的作用就是展示原生路径
            elementPathEnabled:false,
            //设置层级
            zIndex:4,
            //该属性值是服务器统一请求接口路径
            serverURL:common_ops.buildUrl("/upload/ueditor")
        });
zIndex:有时候我们在某些特定的页面,会有一些特殊组件,这些组件可能会被UEditor编辑器覆盖,或者覆盖了UEditor编辑器。这时候就可以给UEditor设置层级,就可以避免这些问题
elementPathEnabled:false,它的作用就是展示原生路径,我们这里进行了屏蔽

<script src="{{ buildStaticUrl('/js/food/set.js') }}"></script>

在前端加载我们的js代码就可以了
完成创建之后的展示

图片上传

我们这里完成之后就要完成图片上传的功能
根据上面的请求路径会返回一个请求值

这个值是可以看见的,我们在后台进行一个配置

当我们进行上传时会返回参数


我们利用files来获取文件名,并利用自己封装的类来进行校验文件格式是否正确,并加上时间

def uploadimage():
    resp = {'state':'SUCCESS','url':'','title':'','original':''}
    #获取传来的图片名称
    file_target = request.files
    #获取图片名
    upfile = file_target['upfile'] if 'upfile' in file_target else None
    #判断是否为空
    if upfile is None:
        resp['state'] = "上传失败"
    #自己封装的类,来进行校验文件格式是否正确
    #我们在这里传输了一个值是文件的名称
    ret = UploadService.uploadByFile(upfile)
    #校验是否正常
    if ret['code'] != 200:
        resp['state'] = "上传失败: " + ret['msg']
        return jsonify(resp)
    resp['url'] = ret['data']['file_key']
    #返回参数
    return jsonify(resp)

class UploadService():
    #静态方法
    @staticmethod
    #创建的函数file用来接收传过来的文件参数
    def uploadByFile(file):
        #UPLOAD = {
        #接收参数的格式
        #  'ext':['jpg','gif','bmp','jpeg','png'],
        #  'prefix_path':'/static/upload/',
        #  'prefix_url':'/status/upload'
        #}
        #这个是在congfig中设置的一个接收参数的格式
        config_upload = app.config['UPLOAD']
        #操作成功之后返回的一个提示
        resp = {'code':200,'msg':'操作成功','data':{}}
        #获取文件名
        filename = secure_filename(file.filename)
        #获取文件后缀名
        ext = filename.rsplit(".",1)[1]
        #判断文件后缀名是否在可接受的范围内
        if not ext in config_upload['ext']:
            resp['code'] = -1
            resp['msg'] = "不允许的文件类型"
            return resp
        #利用root_path来获取本项目的地址,加上config中设置的文件地址
        root_path = app.root_path + config_upload['prefix_path']
        #获取当前时间
        file_dir = getCurrentDate("%Y%m%d")
        #将路径和时间进行拼接
        save_dir = root_path + file_dir
        #判断这个路径是否存在
        if not os.path.exists(save_dir):
            #不存在将创建这个文件
            os.mkdir(save_dir)
            #利用os.chmod给文件赋予权限
            os.chmod(save_dir,stat.S_IRWXU | stat.S_IRGRP | stat.S_IRWXO)
        #利用uuid来生成文件名
        #uuid它可以根据不同时间生成不同数据的一个功能
        file_name = str(uuid.uuid4()).replace("-","")+ "." + ext
        #进行一个文件名的拼接
        file.save("{0}/{1}".format(save_dir,file_name))
        #进行返回
        resp['data'] = {
            'file_key': file_dir + "/" + file_name
        }
        return resp

接下来就是要来进行图片上传之后的展示

def uploadimage():
    resp = {'state':'SUCCESS','url':'','title':'','original':''}
    file_target = request.files
    # print(file_target)
    upfile = file_target['upfile'] if 'upfile' in file_target else None
    if upfile is None:
        resp['state'] = "上传失败"
    #调用uploadByFile生成的图片路径
    ret = UploadService.uploadByFile(upfile)
    if ret['code'] != 200:
        resp['state'] = "上传失败: " + ret['msg']
        return jsonify(resp)
    #把图片路径传到buildImageUrl进行处理
    resp['url'] = UrlManager.buildImageUrl(ret['data']['file_key'])

    return jsonify(resp)
@staticmethod
    def buildImageUrl(path):
        #url = "域名" + "图片前缀" + "key"
        app = create_app("dev")
        #导入config中的定义的app(域名)
        # APP = {
        #     'domain': 'http://127.0.0.1:9090'
        # }
        app_config = app.config['APP']
        #将他们组合
        url = app_config['domain'] + app.config['UPLOAD']['prefix_url'] + path
        return url


就完成了

js代码

var food_set_ops = {
    init: function () {
        this.eventBind();
        this.initEditor();
    },
    eventBind: function () {

    },
    initEditor: function () {
        var that = this;
        that.ue = UE.getEditor('editor', {
            toolbars: [
                [ 'undo', 'redo', '|',
                   'bold', 'italic', 'underline', 'strikethrough', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall',  '|','rowspacingtop', 'rowspacingbottom', 'lineheight'],
                [ 'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
                   'directionalityltr', 'directionalityrtl', 'indent', '|',
                   'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
                'link', 'unlink'],
                [ 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
                    'insertimage', 'insertvideo', '|',
                    'horizontal', 'spechars','|','inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols' ]
            ],
            enableAutoSave:true,
            saveInterval:60000,
            elementPathEnabled:false,
            zIndex:4,
            serverUrl:common_ops.buildUrl("/upload/ueditor")
        });
    }
};

$(document).ready(function () {
    food_set_ops.init();
});

后台代码

@route_upload.route("/upload/ueditor",methods = ["GET","POST"])
def ueditor():
    req = request.values
    # action = request.form.GET("action"," ")
    action = req['action'] if 'action' in req else ''
    if action == "config":
        root_path = app.root_path
        config_path = "{0}/static/plugins/ueditor/upload_config.json".format(root_path)
        print(config_path)
        with open(config_path,encoding="utf-8") as fp:
            try:
                config_data = json.loads(re.sub(r'\/\*.*\*/','',fp.read()))
            except:
                config_data = {}
        return jsonify(config_data)
    if action == "uploadimage":
        return uploadimage()

    return "bfaof"

def uploadimage():
    resp = {'state':'SUCCESS','url':'','title':'','original':''}
    file_target = request.files
    upfile = file_target['upfile'] if 'upfile' in file_target else None
    if upfile is None:
        resp['state'] = "上传失败"
    return jsonify(resp)
posted on   一纸荒年003  阅读(326)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示