Flask 图片上传

upload.html (上传)

{% if msg %} {{ msg }} {% endif %}

在form的标签中写入enctype=multipart/form-data 否则不能上传文件

Show.html (展示)


或者

View.py

ALLOWED_EXTENSIONS = [ 'png', 'jpg', 'gif','bmp']

@blue.route('/upload/',methods=['GET','POST'])
def upload():
    if request.method == 'GET':
        return render_template('upload.html')
    if request.method == 'POST':
        icons = request.files.get('icons')
        #得到上传文件的后缀名
        suffix = icons.filename.rsplit('.',icons.filename.count('.'))[-1]
        #判断上传文件是否是规定格式文件
        if surrix in ALLOWED_EXTENSIONS:
            filename = secure_filename(icons.filename)
            file_path = os.path.join(UPLOAD_DIR,filename)
            icons.save(file_path)
            #保存在数据库
            current_user.icons = os.path.join('upload',filename)
            db.session.add(current_user.icons)
            db.session.commit()
            return redirect(url_for('app.show',filename=filename))
       else:
            msg = '图片上传格式有误,请重新上传'
            return render_template('upload.html',msg=msg)
        

Setting.py (设置路径)

import os

#基础路径
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

#static路径
STATIC_DIR = os.path.join(BASE_DIR,'static')

#templates路径
TEMPLATES_DIR = os.path.join(BASE_DIR,'templates')

#上传路径
UPLOAD_DIR = os.path.join(os.path.join(STATIC_DIR,'media'),'upload')

你可能感兴趣的:(Flask 图片上传)