0

I have been seen so many related questions and I have visited many of them. but none of them solved the problem as most of the solution works around stand alone logic of file uploading. while I am trying to achieve something similar to this

Upload model with IFormFile propertis from Angular2 to ASP.NET Core WebApi

I am working with angular react form where I am submitting a data to a controller of dotnet core. Everything works fine uptil I pass file module

user.model.ts

export class user{

public fullName: string;
public phoneNumber: string;
// etc
//etc
public file File;

}

model on the server

public class User{

public string FullName {get; set;}

public string PhoneNumber{get; set;}

public IFormFile File {get; set;}


   }

End point

public async Task<IActionResult> AddUserDetail(User request)
        {
            if (!ModelState.IsValid)
                return BadRequest("One or more required parameters not passed.");

            var response = await _qaMetricService.AddQAMetricDetail(request);

            return Ok(response);
        }

File upload function in angular file

fileChange = (event: any) => {
    const files: FileList = event.target.files;
    //const fileList = new Array<File>();
    const formData = new FormData();

    for (let i = 0; i < files.length; i++) {
      formData.append(files.item(i).name, files.item(i));
      this.fileList.push(files.item(i));

      console.log(this.fileList);    //working on multiple files before

    }


  }




 OnSubmit(){

    ////All code

    userVM.file = this.fileList[0];


//calling serice 

 this._userService.addUserService(userVM).subscribe((res: APIResponse) => {

});



    }

it did not work.. Now most of the solutions are advising on using FormData.. How would I be able to submit entire model data using FormData at once??

pls someone help me figure out this.

1 Answer 1

1

You can send the whole model like this

const formData = new FormData();
formData.append('fullName ', this.form.get('fullName').value);
formData.append('phoneNumber', this.form.get('phoneNumber').value);
formData.append('file', this.form.get('file').value);
this._userService.addUserService(formData).subscribe(console.log)

if you have multiple file you can append all the files in your formData using [] in the key:

files.forEach((file) => {
 formData.append('file[]' , file, file.name);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.