1

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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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;}
}

6 Comments

I have tried already, I tried a lot of things, but it didn’t work.
Did you try add [FromBody] for example?
Yes, I tryed [FromBody] and [FromForm]
And I don't know what is Restaurant is, but did you try to append it to the form too?
And I am not sure that you need to add const headers = new HttpHeaders().append("Content-Disposition", "multipart/form-data") explicitely
|

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.