Search code examples
angularasp.net-coreform-data

Appending both a file and string data to a FormData object in Angular 9


I am sending a FormData object to my controller in ASP .Net Core from an Angular application. In this FormData object, I would like to append a file which has been uploaded client side and a project id.

uploadLink(files, projectId) {
  if (files.length === 0) {
    return;
  }
  const fileToUpload = files[0] as File;
  const formData = new FormData();
  formData.append('file', fileToUpload, fileToUpload.name);
  formData.append('projectId', projectId);
  return formData;
  }
}

When the data is sent to my controller, I can only see the data from the uploaded file. The project id is not being passed to the controller at all.

    // POST: FileExport/SetReconciliationCSV
    [HttpPost("reconciliation")]
    public async Task<IActionResult> SetReconciliation(IFormFile file)
    {
        fileName = file.FileName;

        var records = new List<ReconciliationExportCsv>();

I am using an IFormFile to receive the data server side. I have checked client side that the correct project id is being passed to the 'uploadLink' method to be appended to the FormData object. Why is the projectId not being passed to my controller?


Solution

  • SOLVED:

    As stated above, the controller was only asking for the file from the FormData object. I was able to retrieve the projectId by adding the parameter '[FromForm]string projectId' to my controller in .net core.

        // POST: FileExport/SetReconciliationCSV
        [HttpPost("reconciliation")]
        public async Task<IActionResult> SetReconciliation(IFormFile file, [FromForm]string projectId)
        {
            fileName = file.FileName;
            string id = projectId;
            var records = new List<ReconciliationExportCsv>();