python flask实战订餐系统微信小程序-45ueditor图片列表在线管理功能

wechat 虚幻 563℃ 0评论

ueditor图片列表在线管理功能

本地上传按钮不能展示的原因解决

应该传递正确图片展示url,他的zurl是这个,只需将它评出来就可以

http://127.0.0.1:8999/static/upload/20210825/efb27551c196435f89a0ecf47d2bedb3.png

UrlManager.py添加静态方法

    @staticmethod
    def buildImageUrl( path ):
        app_config = app.config['APP']
        url = app_config['domain'] + app.config['UPLOAD']['prefix_url'] + path
        return url

base_setting.py添加domain配置

APP = {
    'domain':'http://127.0.0.1:8999'
}

Upload.py添加服务的调用

from common.libs.UrlManager import UrlManager

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)

    ret = UploadService.uploadByFile( upfile )
    if ret['code'] != 200:
        resp['state'] = "上传失败:" + ret['msg']
        return jsonify(resp)

    resp['url'] = UrlManager.buildImageUrl( ret['data']['file_key'] )
    return jsonify( resp )

可以看到成功上傳了

20210826191457 - python flask实战订餐系统微信小程序-45ueditor图片列表在线管理功能

在綫管理功能的添加

创建图片数据库

show databases;
use food_db
CREATE TABLE `images` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `file_key` varchar(60) NOT NULL DEFAULT '' COMMENT '文件名',
  `created_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '插入时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
flask-sqlacodegen "mysql://root:123456@127.0.0.1/food_db" --tables images --outfile "order/common/models/Images.py" --flask

images.pu

# coding: utf-8

from application import db

class Image(db.Model):
    __tablename__ = 'images'

    id = db.Column(db.Integer, primary_key=True)
    file_key = db.Column(db.String(60), nullable=False, server_default=db.FetchedValue(), info='???')
    created_time = db.Column(db.DateTime, nullable=False, server_default=db.FetchedValue(), info='????')

UploadService.py上传成功后需要存储起来:

from common.models.Image 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 ext not in config_upload['ext']:
            resp['code'] = -1
            resp['msg'] = "不允许的扩展类型文件"
            return resp

        root_path = app.root_path + config_upload['prefix_path']
        #不使用getCurrentDate创建目录,为了保证其他写的可以用,这里改掉,服务器上好像对时间不兼容
        file_dir = datetime.datetime.now().strftime("%Y%m%d")
        save_dir = root_path + file_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 ) )

        model_image = Image()
        model_image.file_key = file_dir + "/" + file_name
        model_image.created_time = getCurrentDate()
        db.session.add( model_image)
        db.session.commit()

        resp['data'] = {
            'file_key': model_image.file_key
        }
        return resp

上传测试可以看到成功上传

20210826194507 - python flask实战订餐系统微信小程序-45ueditor图片列表在线管理功能

返回上传的所有图片用于管理

if action == "listimage":
return listImage()

@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
      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 "upload"
from common.models.Images import Image

def listImage():
    resp = { 'state':'SUCCESS','list':[],'start':0 ,'total':0 }

    req = request.values

    start = int( req['start']) if 'start' in req else 0
    page_size = int( req['size']) if 'size' in req else 20

    query = Image.query
    if start > 0:
        query = query.filter( Image.id < start )

    list = query.order_by( Image.id.desc() ).limit( page_size ).all()
    images = []

    if list:
        for item in list:
            images.append( { 'url': UrlManager.buildImageUrl( item.file_key ) } )
            start = item.id
    resp['list'] = images
    resp['start'] = start
    resp['total'] = len( images )
    return jsonify( resp )

运行就可以看到在线管理成功配置了

20210826194959 - python flask实战订餐系统微信小程序-45ueditor图片列表在线管理功能

转载请注明:虚坏叔叔 » python flask实战订餐系统微信小程序-45ueditor图片列表在线管理功能

喜欢 (8)

您必须 登录 才能发表评论!