7

I am new to django. Can anybody help me... How can I upload a file using the Rest Framework API ?

I have tried following this page:

http://www.django-rest-framework.org/api-guide/parsers/#fileuploadparser

Ross Rogers
  • 23,523
  • 27
  • 108
  • 164
user2709881
  • 145
  • 1
  • 1
  • 9

2 Answers2

13

File uploading in Django REST framework is the same with uploading files in multipart/form in django.

To test it you can use curl:

curl -X POST -H "Content-Type:multipart/form-data" -u {username}:{password} \
-F "{field_name}=@{filename};type=image/jpeg" http://{your api endpoint}

Other fields are just like normal form fields in Django.

Zhe Li
  • 1,103
  • 1
  • 14
  • 20
  • 1
    so what if your curl has json data and an image at the same time? – Leonid May 23 '14 at 10:01
  • 1
    I think you can add those data as form field data as well (in -F parameter). Forgot what I did since I haven't been working on REST framework for a few months now. – Zhe Li May 24 '14 at 09:40
  • Leonid: Did you get the answer of your question. can we json data and image at the same time. – vibhor Jun 04 '14 at 04:54
  • 1
    @Leonid check out this code https://github.com/zheli/duego-photo-gallery. I remember I succeed with this one. You can look into the test for upload in rest_api app. – Zhe Li Jun 04 '14 at 12:17
  • @Zhe I can't get the test APIClient to upload files - I keep getting a UnicodeDecodeError on the .post call. Did you have to do anything to get this to work? – Robin Elvin Oct 07 '14 at 14:09
  • @RobinElvin probably because the project was done long time ago and it is out of update now. – Zhe Li Nov 03 '14 at 15:18
2

Zhe answer is pretty well. Besides, you can add some parameters in order to see the response. Take this one for example:

curl -X PATCH --dump-header - -H "Content-Type:multipart/form-data" -u jorge:123456 -F "image=@/home/oscar/Pictures/dgnest/_MG_6445.JPG;type=image/jpeg" http://localhost:8000/api/project/3/
oskargicast
  • 667
  • 1
  • 7
  • 14