python - 上传文件时错误请求(400),Flask

标签 python html file-upload flask bad-request

我正在尝试将文件上传到我的 Flask 后端

我的Python代码

@app.route('/new_upload/', methods=['GET', 'POST'])
@login_required
def upload_file():

    file = request.files['file']
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        flash("File uploaded: Thanks!", "success")
        return redirect(url_for('upload.html'))
    return render_template('upload.html', filename=filename)

我的 HTML 看起来像这样:

{% extends "layout.html" %}
{% from "macros.html" import render_field %}

{% block content %}
<form action="" method=post enctype=multipart/form-data>
      <p><input type=file name=file>
         <input type=submit value=Upload>
</form>
{% endblock %}

在主页中,当我单击上传文件链接时,浏览器会向我显示

Bad Request

The browser (or proxy) sent a request that this server could not understand.

为了方便起见,下面附有主页 HTML 和图像

 <div class="main">

        <nav>

          <a href="{{ url_for('index') }}">All</a>

          {% if current_user.is_authenticated %}
          <a href="{{ url_for('stream', username=current_user.username) }}"> Following</a>
          <a href="{{ url_for('post') }}" class="new">Create New Post</a>
          <a href="{{ url_for('upload_file') }}" class="new">Upload file</a>
          {% endif %}

        </nav>

        {% block content %}{% endblock %}

      </div>

主页

enter image description here

点击后

enter image description here

请尝试帮助我,我刚刚学习

最佳答案

在这段代码

return redirect(url_for('upload.html'))

您应该将 url_for('upload.html') 更改为 url_for('upload') 或函数名称,而不是 html 模板。

此外,如果您打算对 HTTP GET 和 HTTP POST 请求使用相同的函数“def upload_file()”,那么您应该指定将在 post 上执行的代码段以及仅在以下情况下执行的另一段代码:执行 GET 请求。像这样的东西:

# Import request if you haven't.
from flask import request 

@app.route('/new_upload', methods=['GET', 'POST'])
@login_required
def upload_file():

    if request.method == 'POST':
        # This will be executed on POST request.
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            flash("File uploaded: Thanks!", "success")
            return redirect(url_for('upload_file'))

    # This will be executed on GET request.
    return render_template('upload.html')

我还没有测试上面的代码,但如果您使用一个函数来处理 GET 和 POST http 请求,这应该是一种方法。 如果您不区分上传功能(在 POST HTTP 请求上)和呈现模板(在 GET 请求上),它将尝试在每个请求上执行所有代码,并会陷入循环,其中将返回redirect(url_for('upload_file') )每次都不会到达 return render_template('upload.html') ,其中应该显示页面(HTTP 请求使用代码 200 而不是代码 400)。

您可以严格遵循这个示例: http://flask.pocoo.org/docs/0.10/patterns/fileuploads/以获得总体想法。

您还可以查看 HTTP 方法:https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods这样您就可以更好地了解什么是 POST 和 GET 请求。

关于python - 上传文件时错误请求(400),Flask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36233167/

相关文章:

jQuery-File-Upload 插件 - 无法删除文件夹

python - 将一组字典解析为单行 Pandas (Python)

python - 如何创建从 raw_input 创建的字典/列表/类

Python Notebook 定期自动运行

javascript - 在js之前加载css文件

html - 在 chrome 中嵌入 PDF 文件

python - 如何在悬停模板中包含跟踪名称?

html - 图例不会在 IE7 上向左浮动

django - 如何在django中对文件上传进行单元测试

javascript - ExtJs - 从文件字段保存选定的文件