简体   繁体   English

将文件上传到 Flask 时出现 Bad Request 400

[英]Bad Request 400 when uploading file to Flask

I have a Flask server that looks like this:我有一个 Flask 服务器,如下所示:

import flask, os, werkzeug.utils

UPLOAD_FOLDER = "files/"
ALLOWED_EXTENSIONS = {"txt"}

def isFileAllowed(file):
    return str("." in file and file.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS)

app = flask.Flask(__name__)
app.config["UPLOAD_DIR"] = UPLOAD_FOLDER

@app.route("/log_receiver", methods = ["POST", "GET"])
def log_receiver():
    if flask.request.method == "POST":
        file = flask.request.files["file"]
        if file and isFileAllowed(file):
            filename = werkzeug.utils.secure_filename(file)
            file.save(os.path.join(app.config["UPLOAD_DIR"], filename))
            return "Sucessfully uploaded"
        return "File couldn't be uploaded"            
    return "404, not found"
        

if __name__ == '__main__':
    app.run()

I've made a test uploader, also in Python, that looks like this:我做了一个测试上传器,也是在 Python,看起来像这样:

import requests

def log_uploader():
    with open("log.txt", "rb") as log:
        r = requests.post("http://localhost:5000/log_receiver", files={"log.txt": log})
        print(r.text)

if __name__ == '__main__':
    log_uploader()

The issue is, whenever I run it, I get a 404 error.问题是,每当我运行它时,都会收到 404 错误。

I've tried removing the ["file"] in flask.request.files , which removes the 400 error but brings in a 500 error with the following log:我尝试删除flask.request.files中的 ["file"] ,这会删除 400 错误,但会带来 500 错误并显示以下日志:

[2022-11-29 16:05:46,547] ERROR in app: Exception on /log_receiver [POST]
Traceback (most recent call last):
  File "/home/day/.local/lib/python3.9/site-packages/flask/app.py", line 2525, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/day/.local/lib/python3.9/site-packages/flask/app.py", line 1822, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/day/.local/lib/python3.9/site-packages/flask/app.py", line 1820, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/day/.local/lib/python3.9/site-packages/flask/app.py", line 1796, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
  File "/home/day/Desktop/Coding/Quickraft/Server-side/APIs/main.py", line 17, in log_receiver
    filename = werkzeug.utils.secure_filename(file)
  File "/home/day/.local/lib/python3.9/site-packages/werkzeug/utils.py", line 221, in secure_filename
    filename = unicodedata.normalize("NFKD", filename)
TypeError: normalize() argument 2 must be str, not ImmutableMultiDict
127.0.0.1 - - [29/Nov/2022 16:05:46] "POST /log_receiver HTTP/1.1" 500 -

How could I fix this?我该如何解决这个问题? Thanks in advance,提前致谢,
Daymons.戴蒙斯。

See again the flask documentation for request.files再次查看request.files的 flask 文档

Each value in files is a Werkzeug FileStorage object files 中的每个值都是一个 Werkzeug FileStorage object

It is not just the filename but much more than that.它不仅仅是文件名,还远不止于此。 The error message is telling you something: That secure_filename() expects a string, but you are passing it something that isn't a string.错误消息告诉您一些事情: secure_filename()需要一个字符串,但您向它传递的不是字符串。

Have a look again at the flask documentation for file uploads: https://flask.palletsprojects.com/en/2.2.x/patterns/fileuploads/再次查看文件上传的 flask 文档: https://flask.palletsprojects.com/en/2.2.x/patterns/fileuploads/

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

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