The simplest way to use curl to upload a file to python flask server

This is probably the simplest curl command to upload a file:

curl -T x.png http://127.0.0.1:5000/upload/x.png

-T is short for --upload-file.

Flask server for uploading and downloading

Run the following code to launch a flask server:

import os
from flask import Flask, request, url_for
from werkzeug.utils import secure_filename

app = Flask(__name__)
os.makedirs(app.static_folder, exist_ok=True)  # app.static_folder will be used to save uploaded files


@app.route('/upload/<filename>', methods=['PUT'])
def upload(filename):
    filename = secure_filename(filename)  # prevent dangerous name
    with open(os.path.join(app.static_folder, filename), 'wb') as fd:
        fd.write(request.get_data())
    return url_for('static', filename=filename, _external=True)  # return url of uploaded file


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

This server is just used to test. DO NOT use it in production environment. You can refer to https://flask.palletsprojects.com/en/2.1.x/deploying/ for more info.

Put it together

# 1. upload x.png
curl -T x.png http://127.0.0.1:5000/upload/x.png
# 2. download x.png
curl -O http://127.0.0.1:5000/static/x.png
Posted on 2022-04-21