Python Flask網站檔案上傳
阿新 • • 發佈:2018-11-10
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 %}