Upload a file to a python flask server using curl Upload a file to a python flask server using curl flask flask

Upload a file to a python flask server using curl


Your curl command means you're transmitting two form contents, one file called filedata, and one form field called name. So you can do this:

file = request.files['filedata']   # gives you a FileStoragetest = request.form['name']        # gives you the string 'Test'

but request.files['Test'] doesn't exist.


I have had quite a bit of issues getting this to work, so here is a very explicit solution:

Here we make a simple flask app that has two routes, one to test if the app works ("Hello World") and one to print the file name (To ensure we get a hold of the file).

from flask import Flask, requestfrom werkzeug.utils import secure_filenameapp = Flask(__name__)@app.route("/")def hello_world():    return "Hello World"@app.route("/print_filename", methods=['POST','PUT'])def print_filename():    file = request.files['file']    filename=secure_filename(file.filename)       return filenameif __name__=="__main__":    app.run(port=6969, debug=True)

First we test if we can even contact the app:

curl http://localhost:6969>Hello World

Now let us POST a file and get its filename. We refer to the file with "file=" as the "request.files['file']" refers to "file". Here we go to a directory with a file in it called "test.txt":

curl -X POST -F file=@test.txt http://localhost:6969/print_filename>test.txt

Finally we want to use paths to files:

curl -X POST -F file=@"/path/to/my/file/test.txt" http://localhost:6969/print_filename>test.txt

Now that we have confirmed that we can actually get a hold of the file, then you can do whatever with it that you want with standard Python code.