zoukankan      html  css  js  c++  java
  • 一百三十五:CMS系统之UEditoe编辑器集成以及配置将图片上传到七牛

    富文本编辑框,选择UEditor

    下载地址:http://ueditor.baidu.com/website/download.html

    使用说明:http://fex.baidu.com/ueditor/

    使用

    下载下来过后,将指定的几个文件和文件夹拷贝到项目static下

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="{{ url_for('static', filename='ueditor/ueditor.config.js') }}"></script>
    <script src="{{ url_for('static', filename='ueditor/ueditor.all.min.js') }}"></script>
    </head>
    <body>
    <script id="editor" type="text/plain"></script>
    <script>
    var ue = UE.getEditor('editor')
    </script>
    </body>
    </html>

    视图

    from flask import Flask, render_template

    app = Flask(__name__)


    @app.route('/')
    def hello_world():
    return render_template('index.html')


    if __name__ == '__main__':
    app.run()

    运行

     由于没有python版本,所以很多功能用不了

    解决方案,写一个集成的包

    # encoding: utf-8

    from flask import (
    Blueprint,
    request,
    jsonify,
    url_for,
    send_from_directory,
    current_app as app
    )
    import json
    import re
    import string
    import time
    import hashlib
    import random
    import base64
    import sys
    import os
    from urllib import parse

    # 更改工作目录。这么做的目的是七牛qiniu的sdk
    # 在设置缓存路径的时候默认会设置到C:/Windows/System32下面
    # 会造成没有权限创建。
    os.chdir(os.path.dirname(__file__))
    try:
    import qiniu
    except:
    pass
    from io import BytesIO

    bp = Blueprint('ueditor', __name__, url_prefix='/ueditor')

    UEDITOR_UPLOAD_PATH = ""
    UEDITOR_UPLOAD_TO_QINIU = False
    UEDITOR_QINIU_ACCESS_KEY = ""
    UEDITOR_QINIU_SECRET_KEY = ""
    UEDITOR_QINIU_BUCKET_NAME = ""
    UEDITOR_QINIU_DOMAIN = ""


    @bp.before_app_first_request
    def before_first_request():
    global UEDITOR_UPLOAD_PATH
    global UEDITOR_UPLOAD_TO_QINIU
    global UEDITOR_QINIU_ACCESS_KEY
    global UEDITOR_QINIU_SECRET_KEY
    global UEDITOR_QINIU_BUCKET_NAME
    global UEDITOR_QINIU_DOMAIN
    UEDITOR_UPLOAD_PATH = app.config.get('UEDITOR_UPLOAD_PATH')
    if UEDITOR_UPLOAD_PATH and not os.path.exists(UEDITOR_UPLOAD_PATH):
    os.mkdir(UEDITOR_UPLOAD_PATH)

    UEDITOR_UPLOAD_TO_QINIU = app.config.get("UEDITOR_UPLOAD_TO_QINIU")
    if UEDITOR_UPLOAD_TO_QINIU:
    try:
    UEDITOR_QINIU_ACCESS_KEY = app.config["UEDITOR_QINIU_ACCESS_KEY"]
    UEDITOR_QINIU_SECRET_KEY = app.config["UEDITOR_QINIU_SECRET_KEY"]
    UEDITOR_QINIU_BUCKET_NAME = app.config["UEDITOR_QINIU_BUCKET_NAME"]
    UEDITOR_QINIU_DOMAIN = app.config["UEDITOR_QINIU_DOMAIN"]
    except Exception as e:
    option = e.args[0]
    raise RuntimeError('请在app.config中配置%s!' % option)

    csrf = app.extensions.get('csrf')
    if csrf:
    csrf.exempt(upload)


    def _random_filename(rawfilename):
    letters = string.ascii_letters
    random_filename = str(time.time()) + "".join(random.sample(letters, 5))
    filename = hashlib.md5(random_filename.encode('utf-8')).hexdigest()
    subffix = os.path.splitext(rawfilename)[-1]
    return filename + subffix


    @bp.route('/upload/', methods=['GET', 'POST'])
    def upload():
    action = request.args.get('action')
    result = {}
    if action == 'config':
    config_path = os.path.join(bp.static_folder or app.static_folder, 'ueditor', 'config.json')
    with open(config_path, 'r', encoding='utf-8') as fp:
    result = json.loads(re.sub(r'/*.**/', '', fp.read()))

    elif action in ['uploadimage', 'uploadvideo', 'uploadfile']:
    image = request.files.get("upfile")
    filename = image.filename
    save_filename = _random_filename(filename)
    result = {
    'state': '',
    'url': '',
    'title': '',
    'original': ''
    }
    if UEDITOR_UPLOAD_TO_QINIU:
    if not sys.modules.get('qiniu'):
    raise RuntimeError('没有导入qiniu模块!')
    q = qiniu.Auth(UEDITOR_QINIU_ACCESS_KEY, UEDITOR_QINIU_SECRET_KEY)
    token = q.upload_token(UEDITOR_QINIU_BUCKET_NAME)
    buffer = BytesIO()
    image.save(buffer)
    buffer.seek(0)
    ret, info = qiniu.put_data(token, save_filename, buffer.read())
    if info.ok:
    result['state'] = "SUCCESS"
    result['url'] = parse.urljoin(UEDITOR_QINIU_DOMAIN, ret['key'])
    result['title'] = ret['key']
    result['original'] = ret['key']
    else:
    image.save(os.path.join(UEDITOR_UPLOAD_PATH, save_filename))
    result['state'] = "SUCCESS"
    result['url'] = url_for('ueditor.files', filename=save_filename)
    result['title'] = save_filename,
    result['original'] = image.filename

    elif action == 'uploadscrawl':
    base64data = request.form.get("upfile")
    img = base64.b64decode(base64data)
    filename = _random_filename('xx.png')
    filepath = os.path.join(UEDITOR_UPLOAD_PATH, filename)
    with open(filepath, 'wb') as fp:
    fp.write(img)
    result = {
    "state": "SUCCESS",
    "url": url_for('files', filename=filename),
    "title": filename,
    "original": filename
    }
    return jsonify(result)


    @bp.route('/files/<filename>/')
    def files(filename):
    return send_from_directory(UEDITOR_UPLOAD_PATH, filename)
    
    

    配置文件储存目录

    注册蓝图和使用配置

    页面

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <script src="{{ url_for('static',filename='ueditor/ueditor.config.js') }}"></script>
    <script src="{{ url_for('static',filename='ueditor/ueditor.all.min.js') }}"></script>
    <title>Title</title>
    </head>
    <body>
    <script id="editor" type="text/plain"></script>
    <script>
    var ue = UE.getEditor("editor",{
    'serverUrl': '/ueditor/upload/'
    });
    </script>
    </body>
    </html>

    上传图片

    同时,如果不想存在本地,也可以放到七牛云,这里设置了开关

  • 相关阅读:
    拥有自己的代码生成器—Newlife.XCode模板编写教程
    基于Newlife.XCode的权限系统(含数据集权限)【设计篇】
    拥有自己的代码生成器—NewLife.XCode代码生成器分析
    利用javascript来转换GB2312到UNICONDE &#形式
    和荣笔记 从 Unicode 到 GB2312 转换表制作程式
    如何做SVN迁移
    和荣笔记 GB2312 字符集和编码说明
    asp对象化之:基于adodb.stream的文件操作类
    Unicode 汉字内码表
    微软建议的ASP性能优化28条守则 之三
  • 原文地址:https://www.cnblogs.com/zhongyehai/p/11968333.html
Copyright © 2011-2022 走看看