Home > Software design >  Uploading a file in a form group in angular and send it to Django API
Uploading a file in a form group in angular and send it to Django API

Time:08-26

I have a form in the front-end having multiple entries, i.e name, email, phone and also a file field entry. A Form group is used to group all these elements in the same form in Angular. There is also a corresponding model in Django, (Using Django Rest Framework). I could not manage to have the file sent to the API, even if the rest of the data is sent correctly and saved on the back-end.

First, I am able to upload the file successfully to Front-end, below I log in the console: enter image description here

Second, the object I send is something like this:

{"name":"name", "age":49, "email":"[email protected]", "file":File}

The File in the JSON is the same file object displayed in the console above.

I tested my backend with Postman, I was able to succesfully have the file as well as the other data saved. (I believe the problem to be more on the Front-end side ).

Solutions I found for uploading file in Angular used form data (i.e here), these solutions were not convenient as the form consists only of a file, however in my case I have file as well as other data (Form Group).

Another thing I tried that did not work was the following: putting a form Data object with the file in the "file" key of the JSON to be sent. Still, this it did not work.

Also, this is how I upload the file in angular:

   public file: File | null = null;
   public form: FormGroup;
   formData = new FormData();
   
   ngOnInit(){
     this.form = this.fb.group({
            name: [], [Validators.required]],
            age: [],
            email: [], [Validators.required]],
            file: []});
    
    fileUploadedHandler(file) {
        this.file = file;
        this.formData.append("file",file, file.name);
        this.form.patchValue({file:file}); //this.formData});
        this.createDocumentForm.updateValueAndValidity();
        console.log(file);}
  }

Any propositions to solve this ?

CodePudding user response:

Managed to solve the problem. First I had to use formData instead of formGroup, It was also possible to have multiple fields in formData using append method :

this.formData.append("file",file, file.name);
this.formData.append("name",name);
this.formData.append("age",age);

I had also to revisit the HTTP headers used to submit the form to the API, this was the blocking part. In my case I had to Remove the 'Content-Type': 'application/json' from the headers. The new working one was:

working_headers = new HttpHeaders({
    "Accept": "*/*",
    "Authorization": 'Token laksjd8654a6s56a498as5d4a6s8d7a6s5d4a',
  });
  • Related