Python Flask网站文件上传

1、首先在APP的__init__里面配置上传路径

UPLOAD_FOLDER = 'uploads'
APP_DIR=os.path.dirname(__file__)
STATIC_DIR=os.path.join(APP_DIR,"static")

def create_app(config_name):
    app = Flask(__name__)


    #文件上传的绝对上传路径
    app.config['ABS_UPLOAD_FOLDER'] = \
        os.path.join(STATIC_DIR,app.config['UPLOAD_FOLDER'])
    create_folder(app.config['ABS_UPLOAD_FOLDER'])
   

    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    migrate = Migrate(app, db)

2、views里定义上传函数

@firm.route('/uploadcsv', methods = ['GET', 'POST'])
@login_required
def uploadcsv():
    form=UpCSV()  #调用form.py里的UpCSV
    vtitle="批量上传信息"
    if form.validate_on_submit():
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):

            filename = secure_filename(file.filename)
            file_path = os.path.join(app.config['ABS_UPLOAD_FOLDER'],filename)
            flash(file_path)
            file.save(file_path)

            file_url2=url_for("firm.uploaded_file",filename=file.filename)
            return render_template('firm/upload.html',file_url = file_url2,form = form,vtitle=vtitle)
    return render_template('firm/upload.html',form = form,vtitle=vtitle)

 

3、templates里的模板

{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

{% block title %}导入信息{% endblock %}

{% block page_content %}
<div class="col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3">
    <div class="page-header">
    <h1>{{ vtitle }}</h1>
    </div>
    {{ wtf.quick_form(form) }}
    {% if file_url %}
        <h3>已经上传文件到服务器{{ file_url }}</h3>
    {% else %}
        <h3>请上传吧!</h3>
    {% endif %}
</div>

{% endblock %}

猜你喜欢

转载自blog.csdn.net/sharkandshark/article/details/83006262