无法将文件上传到Flask服务器

时间:2019-03-28 19:51:15

标签: python html forms post flask

以下代码假定将所选文件上传到本地Flask服务器。 由于某些未知原因,在按下表单中的“提交”按钮后,request.files为空。我不知道为什么文件路径没有发送到服务器。

Flask服务器的代码

import os
from flask import Flask, flash, redirect, render_template, request, url_for
from werkzeug.utils import secure_filename
UPLOAD_FOLDER = 'C:\Users\user\Desktop\uploads'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS    
@app.route('/uploader', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # 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 an 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.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return render_template('index.html')
return render_template('index.html')


    if __name__ == '__main__':
        app.secret_key = 'super secret key'
        app.debug = True
        app.run()
        app.run(debug=True)

HTML表单代码

<form action="http://localhost:5000/uploader" method="POST" enctype="multipart/form-data">
    <input type="file" name="file" class="custom-file-container__custom 
        file__custom-file-input" id="customFile" accept="*" aria- 
        label="Choose File">
    <input type="hidden" name="MAX_FILE_SIZE" value="10485760"/>
        <input type="submit" value="Press to upload file!">
      </form>

该代码进入第一个“ if”条件,然后停止,就像没有选择任何路径一样。

0 个答案:

没有答案