Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bad Request 400 when uploading file to Flask

I have a Flask server that looks like this:

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:

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

[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.

>Solution :

See again the flask documentation for request.files

Each value in files is a 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.

Have a look again at the flask documentation for file uploads: https://flask.palletsprojects.com/en/2.2.x/patterns/fileuploads/

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading