Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

upload image to imagefield with djangorestframework using json and test this with CURL

I have made several apis in djangorestframework. This I could test both with the html form of the api as with curl in commandline.

Now I have an api to a Model with one off the fields an ImageField.

I can't figure out which curl command to use. Using the syntax I used before fot post actions in json format, it would be:

curl -X POST -S -H 'Content-Type: application/json' -u "username:password" --data-binary '{"otherfields":"something", "photo":"/home/michel/test.jpg"}' 127.0.0.1:8000/api/v1/

but in this case the photo will not be saved and left empty (the photo is an optional field)

adding -T /home/michel/test.jpg I get an error message saying 127.0.0.1:800/api/v1/test.jpg does not exist as an url.

In the test html form of djangorestframework, all works fine.

Using the -F option, it says I can only do 1 request at a time... I also removed the datatype from data-binary

Can anybody help me how to make this curl post with both the image and the other data in json in 1 command.

like image 835
michel.iamit Avatar asked Jul 09 '12 15:07

michel.iamit


1 Answers

After a long puzzle, this seems to do the trick:

  • put all json arguments in separate -F arguments
  • only use the header Accept (not Content-Type)
  • And specify the image type
  • Use @ to indicate the local file to upload

    curl -X POST -S \
      -H 'Accept: application/json' \
      -u "username:password" \
      -F "otherfields=something" \
      -F "photo=@/home/michel/test.jpg;type=image/jpg" \
      http://127.0.0.1:8000/api/v1/
    

By the way, I know all of this is on the documentation site of curl, but just missed an example of all those things together since there are a lot of options to try out.

like image 110
michel.iamit Avatar answered Oct 11 '22 11:10

michel.iamit