Flask无法从HTML识别我的表单[重复]

whhtz7ly  于 2022-12-16  发布在  其他
关注(0)|答案(1)|浏览(98)

此问题在此处已有答案

Sending data from HTML form to a Python script in Flask(2个答案)
(23个答案)
昨天关门了。
我正在为我的web工具开发一个上传文件功能,我遇到了一个问题。问题是Flask没有从HTML表单接收文件。我已经设置了路由,并根据POST方法的要求创建了表单标记,但仍然不起作用。我做错了什么吗?

超文本标记语言

<form action="/" method="POST" enctype="multipart/form-data" class="form-horizontal">
   <div class="row form-group">
      <div class="col-12 col-md-12">
         <div class="control-group" id="fields">
            <label class="control-label" for="field1">
               Requests
            </label>
            <div class="controls">
               <div class="entry input-group upload-input-group">
                  <input class="form-control" name="fields[]" type="file">
                  <button class="btn btn-upload btn-success btn-add" type="button">
                     <i class="fa fa-plus"></i>
                  </button>
               </div>
            </div>
            <button class="btn btn-primary" type="submit" value="Submit">Upload</button>
         </div>
      </div>
   </div>
</form>

**Python/ flask **

import os
from flask import Flask, flash, request, redirect, render_template
from werkzeug.utils import secure_filename

app=Flask(__name__)

app.secret_key = "secret key"
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

path = os.getcwd()
# file Upload
UPLOAD_FOLDER = os.path.join(path, 'uploads')

if not os.path.isdir(UPLOAD_FOLDER):
    os.mkdir(UPLOAD_FOLDER)

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

ALLOWED_EXTENSIONS = set(['xlsx', 'xls'])

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/')
def upload_form():
    return render_template('index.html')

@app.route('/', methods=['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 file.filename == '':
            flash('No file selected for uploading')
            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))
            flash('File successfully uploaded')
            return redirect('/')
        else:
            flash('Allowed file types are xlsx and xls')
            return redirect(request.url)

if __name__ == "__main__":
    app.run(host = '127.0.0.1',port = 5000, debug = False)
vd2z7a6w

vd2z7a6w1#

尝试将输入名称更改为file,而不是fields[]
<input class="form-control" name="file" type="file">

相关问题