Search code examples
javascriptangularmultipartform-dataangular-forms

How to send multiple files FormData where each file belong to a different FormControl?


I'm building a website where a teacher can upload their own course.

Course Structure

CourseName
|-Module1
  |-Lecture 1
  |-Lecture 2
|-Module2
  |-Lecture 1
  |-Lecture 2

The form values structure looks something like

{
  "coursename": "Complete java beginners guide",
  "board": 0,
  "class": 3,
  "coursedescription": "Learn java from scratch",
  "modules": [
    {
      "modulename": "Week 1: Intro to java",
      "lectures": [
        {
          "lecturename": "Data types in Java",
          "lecturepath": {
            "0": {}
          },
          "lecturedescription": "learn datatypes in java"
        },
        {
          "lecturename": "Primary vs Secondary types",
          "lecturepath": {
            "0": {}
          },
          "lecturedescription": "learn about primary vs secondary type"
        }
      ]
    },
    {
      "modulename": "Week 2 some more learning",
      "lectures": [
        {
          "lecturename": "module 2 lecture 1",
          "lecturepath": {
            "0": {}
          },
          "lecturedescription": "learn this lecture"
        }
      ]
    }
  ]
}

where lecturepath holds the file.

I can't figure out how to configure the FormData to send it back to the server.

So far I have this but this, of course, isn't working

onSubmitNewCourse() {
    const formData = new FormData();
    formData.append('course', this.form.value);
    TODO:handle files
  }

Help would be really appreciated :)


Solution

  • Are you sure your file is rightly append to the formData as Blob or Binary?

    For an angular solution I don't know what your application looks like but I proposed you to create a formGroup for all your data and maybe create a service to upload your file into the right course module via the formData like your above code with the file in blob