2

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.

4
  • what kind of parameters the file have? Commented May 4, 2021 at 7:18
  • stackoverflow.com/questions/67264397/… check this Answers Commented May 4, 2021 at 7:19
  • @tmsbrndz - it's a form full of parameters , ints and strings, filles b the user. Commented May 4, 2021 at 7:20
  • Angular 10 to .Net Core Web API Commented May 4, 2021 at 7:23

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

8 Comments

@tmsbrndz- I tried public void FormHandler([FromForm] FileUploadDTO parameters, [FromForm] IFormFile file){ // do the stuff }, the parameters return empty
@tmsbrndz- I updates my question, please check it out, thanks
From where file is coming?
the problem is not with the file bu with the parameters.
uploadFile(event) { this.file = event[0]; }
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.