配置到项目的static中:
下载下来的文件解压然后配置到项目中的static中
效果:
前端文件配置
{% block js %}
<script src="{{ buildStaticUrl('/plugins/ueditor/ueditor.config.js ')}}"></script>
<script src="{{ buildStaticUrl('/plugins/ueditor/ueditor.all.js ')}}"></script>
<script src="{{ buildStaticUrl('/plugins/ueditor/lang/zh-cn/zh-cn.js ')}}"></script>
<script src="{{ buildStaticUrl('/js/food/set.js ')}}"></script>
{% endblock %}
set.js配置
;
var food_set={
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.init();
});
配置ueditor图片上传
从上面图片可以看出当用户上传图片时会携带参数过来,因此我们就可以判断当有这个参数的时候我们接调用保存图片的函数
管理图片功能
后台设置用户可以传的文件后缀名
import json
from flask import Blueprint, request, jsonify,abort
import re
from common.libs.UploadService import UploadService
from common.models.Images import Image
from application import app, db
from common.libs.UrlManager import UrlManager
route_upload=Blueprint("upload_page",__name__)
@route_upload.route("/ueditor",methods=["GET","POST"])
def ueditor():
req = request.values
action = req['action'] if 'action' in req else ''
if action == "config":
root_path = app.root_path
print(root_path)
config_path = "{0}/web/static/plugins/ueditor/upload_config.json".format(root_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()
if action == "listimage":
return listimage()
return "fjowpe"
def uploadImage():
resp={"state":"SUCCESS","url":'',"title":"","original":""}
filer_tager=request.files
upfile= filer_tager["upfile"] if "upfile" in filer_tager else None
if upfile is None:
resp["state"]="上传失败!"
return resp
ret=UploadService.UploadByFile(upfile)
if ret["code"] !=200:
resp["code"] = -1
resp["state"] = "上传失败!"+ret["msg"]
resp["url"]=ret["data"]["file_key"]
resp["url"]= UrlManager.buildImgUrl(ret["data"]["file_key"])
return jsonify(resp)
def listimage():
resp = {"state": "SUCCESS", "list": [], "start": "", "total": ""}
start=request.args.get("start",0)
page_size=request.args.get("size",20)
try:
start=int(start)
page_size=int(page_size)
except Exception as e:
abort(400)
return
query=Image.query
if start>0:
query=query.filter(Image.id<start)
try:
list=query.order_by(Image.id.desc()).limit(page_size).all()
except Exception as e:
abort(400)
return
images=[]
if list:
for item in list:
images.append({"url":UrlManager.buildImgUrl(item.file_key)})
start=item.id
resp["list"]=images
resp["start"]=start
resp["total"]=len(images)
return jsonify(resp)
import os,stat
import uuid
from werkzeug.utils import secure_filename
from application import app, db
from common.libs.Helper import getGreated_date
from common.models.Images import Image
class UploadService:
@staticmethod
def UploadByFile(file):
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=app.root_path.replace("\\","/")+config_upload['prefix_path']
print(app.root_path)
file_dir=getGreated_date()
save_dir=root_path+"/"+file_dir
print(save_dir)
if not os.path.exists(save_dir):
os.mkdir(save_dir)
os.chmod(save_dir,stat.S_IRWXU | stat.S_IRGRP |stat.S_IRWXO)
file_name=str(uuid.uuid4()).replace("_","")+"."+ext
file.save("{0}/{1}".format(save_dir,file_name))
module_image=Image()
module_image.file_key=file_dir+"/"+file_name
module_image.created_time=getGreated_date()
db.session.add(module_image)
try:
db.session.commit()
except Exception as e:
resp["code"] = -1
resp["msg"] = "服务器异常,保存图片失败!"
return resp
resp["data"]={
"file_key":file_dir+"/"+file_name
}
return resp
|