使用flask-dropzone 上傳圖片文件

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

 


如今須要上傳圖片文件的頁面使用jijin2渲染,因爲是使用flask-dropzone的,因此咱們使用dropzone的css和js 來進行一個渲染html

 

首先數據庫

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

# 再用這個指定進行上傳的視圖函數 在action中指定
{{ dropzone.create(action=url_for("user.upload")) }}

在給個頁面上傳文件會到指定的函數中去flask

例子爲session

@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()
相關文章
相關標籤/搜索