Upload image to Django Rest Framework using angular

Viewed 11

I'm using Django rest framework to create my api I have a model which receive an ImageField, if I tested the url with postman and attaching the image with the form-data works perfectly but when using angular as the frontend to send the image I get the following error:

Image: Array ['Image is not a file: check the method of codification of the formulary']

Here is my onSubmit method

  add(endpoint:string, data:any) {
    let url = `${this.baseUrl}/${endpoint}/`
    let datos = JSON.stringify(data)
    let token = new HttpHeaders().set('Content-Type', 'application/json').set('Authorization', `Token ${localStorage.getItem('token')}`)
    let options = {headers:token}
    return this.http.post(url, datos, options).pipe(catchError(this.handleError<any>()))
  }

After debugging I noticed that the image field was empty so it's not sending any information but this happens just when I use the JSON.stringify(), is there anyway I could handle this?

I have also tried to use the FormData method but this then gave me a JSON Parse Error.

Model.py:

class Pelicula(models.Model):
    titulo = models.CharField(max_length=100)
    descripcion = models.TextField()
    imagen = models.ImageField(upload_to='peliculas', null=True, blank=True)
    reparto = models.TextField()
    director = models.CharField(max_length=100)
    duracion = models.IntegerField()
    genero = models.CharField(max_length=100)

Serializer:

class PeliculaSerializer(serializers.ModelSerializer):
    class Meta:
        model = Pelicula
        fields = ('titulo', 'imagen', 'descripcion', 'reparto', 'genero', 'duracion', 'director')
1 Answers

init the form

ngOnInit() {
    this.form = this.formBuilder.group({
      profile: ['']
    });
  }

attach this event to the file input. Here we are setting the file into the form

onChange(event) {
    if (event.target.files.length > 0) {
      const file = event.target.files[0];
      this.form.get('profile').setValue(file);
    }
  }


onSubmit() {
    const formData = new FormData();
    formData.append('file', this.form.get('profile').value);

    this.uploadService.upload(formData).subscribe(
      (res) => {
        this.response = res;
        this.imageURL = `${this.DJANGO_SERVER}${res.file}`;
        console.log(res);
        console.log(this.imageURL);
      },
      (err) => {  
        console.log(err);
      }
    );
  }

upload function from upload service

public upload(formData) {
    return this.http.post<any>(`${this.DJANGO_SERVER}/upload/`, formData);
}
Related