1

I have an image field using django-rest-framework how to I handle the uploading of images over the API?

Is there any examples?

models.py

image = models.ImageField(
        upload_to="profiles",
        height_field="height",
        width_field="width",
        null=True,
        blank=True,
        editable=True,
        help_text="Profile Picture",
        verbose_name="Profile Picture"
    )
    height = models.PositiveIntegerField(null=True, blank=True, editable=False)
    width = models.PositiveIntegerField(null=True, blank=True, editable=False)
jason
  • 2,895
  • 8
  • 26
  • 38
  • 1
    http://stackoverflow.com/questions/11398696/upload-image-to-imagefield-with-djangorestframework-using-json-and-test-this-wit – catherine Feb 28 '13 at 15:38

2 Answers2

2

Finally I am able to upload image using Django. Here is my working code

views.py

class FileUploadView(APIView):
# parser_classes = (MultiPartParser, FormParser, )
parser_classes = (FileUploadParser, )

# media_type = 'multipart/form-data'
# format = 'jpg'

def post(self, request, format='jpg'):
    up_file = request.FILES['file']
    destination = open('/Users/Username/' + up_file.name, 'wb+')
    for chunk in up_file.chunks():
        destination.write(chunk)
        destination.close()

    # ...
    # do some stuff with uploaded file
    # ...
    return Response(up_file.name, status.HTTP_201_CREATED)

urls.py

urlpatterns = patterns('', 
url(r'^imageUpload', views.FileUploadView.as_view())

curl request to upload

curl -X POST -S -H -u "admin:password" -F "file=@img.jpg;type=image/jpg" 127.0.0.1:8000/resourceurl/imageUpload
Vipul J
  • 6,641
  • 9
  • 46
  • 61
0

The image field doesn't store the image but rather a link to it. Do you have MEDIA_URL set in settings? eg MEDIA_URL = '/media/' If you're running on localhost you should find the image at localhost/media/profiles/image_name.png

Cathal
  • 1,740
  • 18
  • 31