• 使用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()
  • 相关阅读:
    RESTful API
    访问方式由http改为https curl:(51)
    java.lang.OutOfMemoryError: PermGen space
    liunx下tomcat启动 Cannot find ./catalina.sh
    Java-编译后出现$1.class、$2.class等多个class文件
    错误处理的返回--异常还是返回值
    ubuntu 上安装温度检测
    mysql5.6不能输入中文
    jmap在ubuntu上DebuggerException: Can't attach to the process
    tomcat-reload-与内存泄露
  • 原文地址:https://www.cnblogs.com/zengxm/p/11211308.html
Copyright © 2020-2023  润新知