chana
chana

Reputation: 241

Upload file with parameters Angular 10 to .Net Core Web API using FormData

I am looking for a way to attach parameters form along with a file using FormData.

so I have a file input and a form with many parameters.

this is how I send my file:

 let formData=new FormData();
 formData.append("file",<File>this.file);

this is my form:

 this.fileForm = this.fb.group({
  headline: [],
  fileType: [],
  fileCategory: [],
  fileEssence: []
});

I tried to add the form value like this:

 formData.append("params",this.fileForm.value);

but I can't find it in the c# code:

var form= Request.Form;

only brings the file object.

Is there another way to do this?

update:

this is my upload function in angular:

  save(){
   let formData=new FormData();
   formData.append("file",<File>this.file);
   formData.append("parameters",this.fileForm.value);
   this.fileService.uploadFile(formData).subscribe((res)=>{
  console.log(res);
})

}

file service:

 uploadFile(fileUpload: any): Observable<any> {
    return this.http.post(ApiConsts.uploadFile, fileUpload).pipe(
        map((res: any) => res))
}

C# function:

   public IActionResult UploadFile([FromForm] FileUploadDTO parameters, [FromForm] IFormFile file)
    {
    }

FileUploadDTO class:

public class FileUploadDTO
{
 
    public FileCategory fileCategory { get; set; }
    public FileEssence fileEssence { get; set; }
    public FileType fileType { get; set; }
    public string  headline { get; set; }

}

the parameters var is empty, not null but all values are null.

Upvotes: 2

Views: 2272

Answers (1)

tmsbrndz
tmsbrndz

Reputation: 1347

To formData you can append blob or string. So you can append values to formData and send it to backend. At backend you can get post parameters via FromForm attribute.

Here is my example:

const formData = new FormData(); 
formData.append('file', this.file);
formData.append('fileType', this.fileForm.get('fileType').value);
formData.append('fileCategory', this.fileForm.get('fileCategory').value);

Get formData on backend:

public void FormHandler([FromForm] string fileType, [FromForm] string fileCategory, [FromForm] IFormFile file){
// do the stuff
}

Upvotes: 2

Related Questions