【问题标题】:Flask/Apache submit button for file upload用于文件上传的 Flask/Apache 提交按钮
【发布时间】:2014-07-20 19:13:43
【问题描述】:

我有一个在 apache 后面运行的烧瓶应用程序,在我的 index.html 页面上我有一个文件上传按钮和一个提交按钮,如下所示:

<form id="package_form" action="" method="POST">
  <div>
    <p>Upload Packages:</p>
    <p><input id="upload_button" type="file" class="btn btn-default btn-xs"></p>
    <p><input id="submit_button" type="submit" class="btn btn-success" value="Upload">
  </div>
</form>

我希望它会发送 post 请求,flask 会捕获它并上传文件,如下所示:

from flask import render_template, request, Response, url_for
from app import app
from werkzeug import secure_filename

## uploading specs ##
UPLOAD_FOLDER = '/tmp/'
ALLOWED_EXTENSIONS = set(['deb'])

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

## index page stuff ##
@app.route('/index', methods = ['GET', 'POST'])
def index():
## kerberos username
    secuser = request.environ.get('REMOTE_USER')

    user = { 'nick': secuser }


## file uploading stuff
if request.method == 'POST': 
    file = request.files['file']
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(UPLOAD_FOLDER, filename))
        return redirect(url_for('/index',     
                        filename=filename))

## main return
return render_template("index.html",
    user = user)

上传文件按钮运行良好,一切正常,只是按下提交按钮时出现 400 错误,所以它必须是烧瓶方面的东西,但我不太确定可能是什么。

任何帮助将不胜感激:)

【问题讨论】:

    标签: python apache flask


    【解决方案1】:
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join("/tmp/", filename))
    

    这就是诀窍!

    虽然你还需要将这个添加到 index.html (name="file" 到upload_button)

    <form id="package_form" action="" method="POST">
      <div>
        <p>Upload Packages:</p>
        <p><input id="upload_button" type="file" class="btn btn-default btn-xs" name="file"></p>
        <p><input id="submit_button" type="submit" class="btn btn-success" value="Upload">
      </div>
    </form>
    

    【讨论】:

      【解决方案2】:

      当您在表单中包含文件输入时,您需要将enctype="multipart/form-data" 添加到表单标签本身,以告诉浏览器以正确的格式发送内容。

      【讨论】:

      • 感谢您的回复!我添加了它,但我仍然收到“错误请求”页面
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多