0

I have a problem, I need to pass model as first a parameter, and as the second parameter, I need to pass a file

Adding a file to a form:

const formDate = new FormData();
formDate.append("File", this.file);

Sending data from angular:

this.dataService.createRestaurant(this.restaurant, formDate)
    .subscribe((data: Restaurant) => this.loadProducts(data))

Data sending service:

createRestaurant(model: Restaurant, form: FormData){
  const headers = new HttpHeaders().append("Content-Disposition", "multipart/form-data")
    return this.http.post(this.url, {model, form}, {headers: headers});
  }

Controller in Asp.net core:

public IActionResult Post(Restaurant restaurant, IFormFile File)
    {
       code...
    }

I tried to solve this problem for two days, the model is transferred normally, but the file is always null

R. Richards
  • 24,603
  • 10
  • 64
  • 64
Betsq9
  • 135
  • 1
  • 3
  • 11

2 Answers2

1

This is how you shape the data into a form

const formDate = new FormData();
formDate.append("restaurant", JSON.stringify(this.restaurant));
formDate.append("file", this.file[0], this.file[0].name);

"this.restaurant" is exactly the same data model as in Asp.Net Core

Accept json data as in this question: ASP.NET Core and formdata binding with file and json property

Betsq9
  • 135
  • 1
  • 3
  • 11
0

Try to change your action to this:

public IActionResult Post(RestaurantViewModel viewModel)
    {
       code...
    }

by creating a ViewModel

public RestaurantViewModel
{
public Restaurant restaurant {get; set;}
public IFormFile File {get; set;}
}
Serge
  • 40,935
  • 4
  • 18
  • 45