2

I'm using Django REST API and Angular 6 for the frontend.

I have defined an ImageField in the Profile model which accepts File input.

In angular application, I'm generating File object from the Base64 image data and sending to the endpoint with header as Content-Type: 'multipart/form-data'

The data sent is

enter image description here

where first_name and profile.avatar are the form fields and profile.avatar contains the image file.

But in the network tab the parameters sent for profile.avatar is empty dictionary.

enter image description here

How can I send media file as form-data from Angular to REST API?

Edit 2: Code

submit() {

    // call method that creates a blob from dataUri
    // imgSrc[0] contains base64 string
    const imageBlob = this.dataURItoBlob(this.imgSrc[0]);

    const extension = imageBlob['type'].split('/')[1];
    const imageName = 'file123' + '.' + extension;

    const imageFile = new File([imageBlob], imageName, { type: imageBlob['type'] });

    const fb = new FormData();
    fb.append('profile.avatar', imageFile, imageFile.name);

    this.account.updateProfile(fb, {headers: {'Content-Type': 'multipart/form-data'}}).subscribe(
        res => {
          console.log(res);
        },
        error => {
          console.log(error);
        }
    );
  }


  dataURItoBlob(dataURI: string) {
    // Split from , (comma)
    const b64Split = dataURI.split(',');

    const extension = 'png';

    // remove data:image/png;base64, from the base64 string
    dataURI = dataURI.replace(b64Split[0] + ',', '');

    const byteString = atob(dataURI);
    const arrayBuffer = new ArrayBuffer(byteString.length);
    const int8Array = new Uint8Array(arrayBuffer);

    for (let i = 0; i < byteString.length; i++) {
      int8Array[i] = byteString.charCodeAt(i);
    }
    const blob = new Blob([arrayBuffer], { type: 'image/png' });

    return blob;
  }

The updateProfile method is sending data using PATCH method.

Anuj TBE
  • 9,198
  • 27
  • 136
  • 285

1 Answers1

0

I was running into the exact same issue. In my request header, I had specified a content-type. Once I removed that, I was able to send both text fields and a file. For your post request, you must also be using formData like so:

let formData = new FormData();
formData.append('textOrFileField', yourTextOrFile);

Hope this helps!

Naser AlOqab
  • 499
  • 4
  • 9