Curl how to POST multipart/form-data data and How to Read multipart/form-data in flask request
There are a few problems with your curl command, all of which might contribute to the problem:
application/multipart/form-data
is not a valid MIME type, so theContent-Type
is invalid. For file uploads the content type would usually bemultipart/form-data
. Also, you don't need to specify the content type, curl will work it out based on the arguments.- Using
-F
instead of-d
will cause curl to generate and post amultipart/form-data
form with a valid boundary. - A name should be specified for each form field.
Putting that together results in this curl command:
curl -i -H "Authorization":"eyJhbGciOiJIUzI1NiIsImV4cCI6MTQyNjcwNTY4NiwiaWF0IjoxNDI2NzAyMDg2fQ.eyJpZCI6MTc3fQ.yBwLFez2RnxTojLniL8YLItWVvBb90HF_yfhcsyg3lY" \ -F user_data='{"user data": {"preferred_city":"Newyork","within_radious":"5"}}' \ -F uploaded_documents=@mydocument.pdf \ http://127.0.0.1:5000/api/city
You can specify the content type for each part if you don't like the ones selected by curl (the file will be application/octet-stream):
curl -i -H "Authorization":"eyJhbGciOiJIUzI1NiIsImV4cCI6MTQyNjcwNTY4NiwiaWF0IjoxNDI2NzAyMDg2fQ.eyJpZCI6MTc3fQ.yBwLFez2RnxTojLniL8YLItWVvBb90HF_yfhcsyg3lY" \ -F 'user_data={"user data": {"preferred_city":"Newyork","within_radious":"5"}};type=application/json' \ -F 'uploaded_documents=@mydocument.pdf;type=application/pdf' \ http://127.0.0.1:5000/api/city
The last command would generate a HTTP request like this:
POST /api/city HTTP/1.1User-Agent: curl/7.32.0Host: 127.0.0.1:5000Accept: */*Authorization:eyJhbGciOiJIUzI1NiIsImV4cCI6MTQyNjcwNTY4NiwiaWF0IjoxNDI2NzAyMDg2fQ.eyJpZCI6MTc3fQ.yBwLFez2RnxTojLniL8YLItWVvBb90HF_yfhcsyg3lYContent-Length: 496Expect: 100-continueContent-Type: multipart/form-data; boundary=------------------------1ab997efff76fe66--------------------------1ab997efff76fe66Content-Disposition: form-data; name="user_data"Content-Type: application/json{"user data": {"preferred_city":"Newyork","within_radious":"5"}}--------------------------1ab997efff76fe66Content-Disposition: form-data; name="uploaded_documents"; filename="mydocument.pdf"Content-Type: application/pdfthis is the mydocument.pdf file.it should be a pdf file, but this is easier to test with.--------------------------1ab997efff76fe66--
Then in Flask you can access the form data using request.form
, e.g. request.form['user_data']
. As it is a json string, you could load it using json.loads(request.form['user_data'])
.
The uploaded file can be accessed by using request.file
as described here and here in the Flask documentation.