我正在尝试将文件上传到我的 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>
主页
点击后
请尝试帮助我,我刚刚学习
最佳答案
在这段代码
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/