Angular 5 image upload recipe

To prepare our html to upload images we would need to add input field to our html.

<input type="file" class="form-control" name="logo" required (change)="handleFileInput($event.target.files)" >

When file is changed it is going to call a function. We would need to define that function at our component.

 
 image_to_upload: File = null;
 handleFileInput(files: FileList) {
   this.image_to_upload = files.item(0);
 }

 create(image_data) {
   this.image_service.uploadImage(this.image_to_upload, image_data);
 }

Then at our service we would need to make the post request.

uploadImage(fileToUpload, image_data) {
  const endpoint = 'http://localhost:8000/image/';

const formData: FormData = new FormData();

  for(const k in image_data){
    formData.append(k, image_data[k]);
  }

  formData.append('image', fileToUpload, fileToUpload.name);
  console.log(formData);
   return this.http
    .post(endpoint, formData).toPromise().then(
      (res) => {
        console.log(res);
      }
    );
 }

Which will be sufficient for any API that accepts POST request:

{
 image: 
}

If we want to implement it using django, it would look like following:

Django model:

class Image(models.Model):
    image = models.FileField(storage = MyStorage(location="media/shop"))

Django Rest Framework serializers and viewsets:

class ImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Image
        fields = ('id','logo',)

class ImageViewSet(viewsets.ModelViewSet):
    queryset = Image.objects.all()
    serializer_class = ImageSerializer

router = routers.DefaultRouter()
router.register(r'image', ImageViewSet)

urlpatterns = router.urls