使用flask-dropzone 上传图片文件

引用  http://greyli.com/flask-dropzone/


现在需要上传图片文件的页面使用jijin2渲染,由于是使用flask-dropzone的,所以我们使用dropzone的css和js 来进行一个渲染

首先

# 先添加这个 css,js 和样式
{{ dropzone.load_css() }}
    {{ dropzone.load_js() }}
    {{ dropzone.style('border: 2px dashed #0087F7; margin: 10%') }}

# 再用这个指定进行上传的视图函数 在action中指定
{{ dropzone.create(action=url_for("user.upload")) }}

在给个页面上传文件会到指定的函数中去

例子为

@user.route('/upimage/',methods=['GET','POST'])
@login_required
def upload():

    if request.method == 'POST':
        f = request.files.get('file')  # 获取文件对象

        # 创建文件夹
        basefile = os.path.join(os.path.abspath('static'),'image')
        if not os.path.exists(basefile):
            os.mkdir(basefile)

        # 验证后缀
        ext = os.path.splitext(f.filename)[1]
        if ext.split('.')[-1] not in UPLOAD_IMAGE_TYPE:
            return 'Image only!', 400

        # 生成文件名  使用uuid模块
        filename = get_uuid(ext)
        path = os.path.join(basefile,filename)
        f.save(path)
    
    # 将文件路径保存到定义的模型中,这里我定义了一个用户类,一个图片路径类,current_user 是flask_login带的当前用户信息
curent_user_tosave_imagepath(current_user,path)
return render_template('upload.html')
UPLOAD_IMAGE_TYPE 为自定义类型,不使用dropzone的

# 设置的图片上传 限制后缀
UPLOAD_IMAGE_TYPE = ['JPG','GIF','PNG','png','jpg','gif','JPEG','jpeg']

# 如果有其他需求,比如文本,视频,则可以一样定义
UPLOAD_VIDEO_TYPE = ['MP4','mp4','xxx','xxx','xx','xx','xx','x']
curent_user_tosave_imagepath
curent_user_tosave_imagepath   保存图片路径到数据库


def curent_user_tosave_imagepath(current_user,path):
    img = Image()
    img.img_path = path
    img.user_id = current_user.id

    try:
        db.session.add(img)
        db.session.commit()
    except:
        db.session.rollback()
原文地址:https://www.cnblogs.com/zengxm/p/11211308.html