Uploading File to Flask with Python and curl


Recently, I tried to create a small Flask endpoint for a python application which should be able to handle file uploads. Copying the example from the official documentation didn’t work as expected, so I started a long search for answers on Developers Favorite Website (stackoverflow.com).

TL/DR: My endpoint was working fine, but I didn’t use curl with the correct flags.

This does not work

curl -X POST localhost:5000/upload --upload-file 'data.csv' -i

Why is there even an --upload-file flag, if you can’t use it?

The solution looks like this

Python/flask endpoint:

ALLOWED_EXTENSIONS = ['csv', 'txt']

def allowed_filename(filename: str) -> bool:
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route('/upload', methods=['POST'])
    def upload_csv(id: int) -> str:
        submitted_file = request.files['file']
        if submitted_file and allowed_filename(submitted_file.filename):
            filename = secure_filename(submitted_file.filename)
            directory = os.path.join(app.config['UPLOAD_FOLDER'], str(id))
            if not os.path.exists(directory):
            submitted_file.save(os.path.join(directory, filename))
            out = {
                'status': HTTPStatus.OK,
                'filename': filename,
                'message': f"{filename} saved successful."
            return jsonify(out)

curl command:

curl -X POST localhost:5000/upload -F 'file=@data.csv' -i

If this post was helpful to you, you can buy me a drink via BTC at 3JZarpMiw56ArjrjAb9GXjMjtbzx8BgzC3 or VTC at VmopwLohPZnWqb7pMUT2ZH29diogAnEqga