Forums

Upload multiple files Flask

I am trying to use flask to upload from a client PC to my pythonanywhere server. I'm not getting an error code so not sure where I'm going wrong.

So from the client I want to upload 2 images catt and catt2

import requests
test_files = [('cat1', open("catt.jpg", "rb")),
              ('cat2', open("catt2.jpg", "rb"))]
response = requests.post("http://jamesb67.eu.pythonanywhere.com/upload", files = test_files)

Then on the server side I have

app = Flask(__name__)

UPLOAD_FOLDER = '/home/Jamesb67/mysite/uploads'
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route("/upload", methods=["POST"])
def upload():
    uploaded_files = flask.request.files.getlist("files")
    print(uploaded_files)
    for file in uploaded_files:
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    return "File saved successfully"

I get a status code 200 when I check it and there is no error on my end. I have a folder called "uploads" on the website that I would expect the files to be saved to. But the code runs without an error and I'm not sure where I've went wrong?

Also is this the best way to go about things? Ideally I don't actually want to save the files I'd prefer to keep them as a variable that can be used for processing later.

If the code doesn't raise an exeption while processing the request it will always return 200 even if the uploaded_files is an empty list, because it's how it's written. To ease the debugging process, redirect logging to your error log with print(uploaded_files, file=sys.stderr) (and import sys at the beginning of the file). Then check what is printed in the error log (you'll find link to it on your Web page) -- if the list is empty, it means that the code is not doing what you want it do.

@pafk

Thanks for the response. I did as you suggested and got an empty list "2021-08-20 10:15:56,293: []"

Can you see a reason why it isn't working?

For one file the following worked no problem.

files = {'media': open('catt.jpg', 'rb')}
response = requests.post("http://jamesb67.eu.pythonanywhere.com/upload", files=files)

I'd suggest looking at the getlist method documentation -- you probably need to craft the request differently.

@pafk

Yes! That was it. It was the naming

test_files = {('cat', open("catt.jpg", "rb")),
          ('cat', open("catt2.jpg", "rb"))}

then

uploaded_files = flask.request.files.getlist("cat")

and it saved

Glad to hear that you made it work!