Append FormData With Object Having Array Property and Array Element With File Property

How to append an object to FormData where the object has a property of type array and each element in the array has a property of type file.

I am trying this from an Angular app with backend in .net5 API. The controller binds FilesReques.Id but not AddedFiles.

I have tried few solutions from here also tried this library.

C# Models

    public class FilesRequest
    {
        public string Id { get; set; }
        public IList<AddedFile> AddedFiles { get; set; }
    }

    public class AddedFile
    {
        public string SomeProperty1 { get; set; }
        public string SomeProperty2 { get; set; }
        public IFormFile File { get; set; }
    }

Controller action:

        [HttpPost]
        [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(bool))]
        public async Task<bool> Process( [FromForm] FilesRequest filesRequest)
        {
            // Process
            return true;
        }

TypeScript:

data:any = {
    id:'xxxxxxx',
    addedFiles:[]
  }

onFileSelect(event:any){
    const file = event.target.files[0]; 
    this.data.addedFiles.push(
      {
        'someProperty1 ':'value1',
        'someProperty2 ':'value2',
        'file':file
      }
    );
  }

  postRequest(){
    const formData = new FormData();
    formData.append('id', this.data.id);
    // How to appent data.addedFiles to formData?
    //Post data
  }

It works fine in the following form i.e. Id and files are bound on receiving the request in the controller action:

    public class FilesRequest
    {
        public string Id { get; set; }
        public IList<IFormFile> files { get; set; }
    }

    simpleData:any = {
       id:'xxxxxxx',
       files:[]
    } 

  onFileSelect(event:any){
    const file = event.target.files[0]; 
    this.simpleData.addedFiles.push(file);
  }

   postRequest(){
    const formData = new FormData();
    formData.append('id', this.simpleData.id);    
    this.simpleData.files.forEach((file: any) => {
      formData.append('files', file);
    });
    
    //Post data
  }


from Recent Questions - Stack Overflow https://ift.tt/2P7SLcx
https://ift.tt/eA8V8J

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Hibernate Search - Elasticsearch with JSON manipulation

Spring Elasticsearch Operations