Proper way to save image from front end app to backend API

Published

In my case I’m using AngularJS and Django backend with Django Rest framework. So I need to save a Profile data with image. My model in database looks like:

class Profile(models.Model):
    first_name = models.CharField()
    avatar = models.ImageField()

But I can’t decide what a best way to save this image on front end.

Solution 1 – Convert image to base64 and create Base64Serializer in Django:

https://xploit29.com/2016/09/13/upload-files-to-django-rest-framework-using-angularjs/

For me the most easy way

Solution 2 – Multipart/form-data File Upload with AngularJS

https://withintent.uncorkedstudios.com/multipart-form-data-file-upload-with-angularjs-c23bf6eeb298

I don’t like the things like:

$http.post(uploadUrl, fd, {
    transformRequest: angular.identity,
    headers: {'Content-Type': undefined} 
}) 

Looks like hack. And the same on backend side. We need to use https://www.django-rest-framework.org/api-guide/parsers/#multipartparser

Solution 3 – Create a separate view to upload files and change database to:

class Image(models.Model):
   image = models.ImageField()

class Profile(models.Model):
    first_name = models.CharField()
    avatar = models.ForeignKey('Image', null=True, blank=True, on_delete=NULL)

It is complicate to use on existing database, but seems very flexible. But also using solution 2 to implement file upload

Source: New feed
Source Url Proper way to save image from front end app to backend API

Published
Categorized as angularjs, django, django-rest-framework

Answers

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq