简体   繁体   English

上传文件,烧瓶时请求(400)错误

[英]Bad Request(400) when upload file, Flask

I'm trying to do a file upload to my Flask backend 我正在尝试将文件上传到我的Flask后端

My Python code 我的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)

My HTML looks like this: 我的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 %}

In home page when I clicked on upload file link browser show me 在主页上,当我单击上传文件链接浏览器时,向我显示

Bad Request 错误的请求

The browser (or proxy) sent a request that this server could not understand. 浏览器(或代理)发送了该服务器无法理解的请求。

For clearance Home page HTML and image are attached bellow 为了清楚起见,下面附有主页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>

Home Page 主页

在此处输入图片说明

After click 点击后

在此处输入图片说明

Please try help me, I am just learning 请尝试帮助我,我正在学习

In this piece of code 在这段代码中

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

You should change url_for('upload.html') to url_for('upload') or what is suppose to be the name of the function instead of the html template. 您应该将url_for('upload.html')更改为url_for('upload')或假设是函数名称而不是html模板的名称。

Also if you are about to use the same function "def upload_file()" for HTTP GET and HTTP POST requests, then you should specify the piece of code that would be executed on post and another piece that would be executed when only GET request is performed. 另外,如果您要对HTTP GET和HTTP POST请求使用相同的函数“ def upload_file()”,则应指定将在发布时执行的代码段和仅在GET请求被执行时执行的另一段代码执行。 Something like: 就像是:

# 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')

I haven't tested the above code, but this should be the approach if you use one function for GET and POST http request. 我尚未测试以上代码,但是如果您对GET和POST http请求使用一个功能,则应该采用这种方法。 If you do not differentiate the upload functionality (on POST HTTP request) and rendering the template (on GET request) it would try to execute all the code on every request and would fall in loop where would return redirect(url_for('upload_file')) every time and would not get to the return render_template('upload.html') where is suppose to show you page (HTTP request with code 200 instead of code 400). 如果您不区分上传功能(针对POST HTTP请求)和呈现模板(针对GET请求),它将尝试在每个请求上执行所有代码,并且会陷入循环,并在其中返回redirect(url_for('upload_file') ),并且每次都不会返回到render_template('upload.html')返回的位置,该页面应该向您显示页面(使用代码200而不是代码400的HTTP请求)。

You can strictly follow this example: http://flask.pocoo.org/docs/0.10/patterns/fileuploads/ to get the overal idea. 您可以严格遵循以下示例: http : //flask.pocoo.org/docs/0.10/patterns/fileuploads/以获取总体思路。

You can also have a look at the HTTP Methods: https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods so you would have better overview what is POST and GET request. 您还可以查看HTTP方法: https : //en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods,因此您可以更好地了解什么是POST和GET请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM