I'm having a problem with IFormFile and FormData.
When I submit a file using FormData, the mapped Object returns a null value in the Backend.
I provide a code sample so that you may review my code.
Angular:
upload(prod: Product) {
let formData = new FormData();
formData.append("productName", prod.productName);
formData.append("productSku", prod.productSku);
for(let i=0;i<prod.variants.length;i ){
formData.append(`variants[${i}][variantName]`, prod.variants[i].variantName);
formData.append(`variants[${i}][media][fileName]`, prod.variants[i].media.fileName);
formData.append(`variants[${i}][media][mediaFile]`, prod.variants[i].media.mediaFile);
}
console.log(prod);
this.http.post('https://localhost:7255/api/products', formData)
.subscribe(res => {
console.log(res);
alert('Uploaded Successfully.');
})
}
ASP.Net Core
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
public ProductsController() {}
[HttpPost]
public IActionResult Post([FromForm] ProductCreateDto product )
{
return Ok();
}
}
public class ProductCreateDto
{
[JsonProperty("productName")]
public string? ProductName { get; set; }
[JsonProperty("productSku")]
public string? ProductSku { get; set; }
[JsonProperty("variants")]
public IEnumerable<Variant> Variants { get; set; }
}
public class Media
{
[JsonProperty("fileName")]
public string? FileName { get; set; }
public IFormFile? MediaFile { get; set; }
}
public class Variant
{
[JsonProperty("variantName")]
public string? VariantName { get; set; }
[JsonProperty("media")]
public Media? Media { get; set; }
}
When I update the code and I put a IFormFile in the DTO it works
public class ProductCreateDto
{
[JsonProperty("productName")]
public string? ProductName { get; set; }
[JsonProperty("productSku")]
public string? ProductSku { get; set; }
[JsonProperty("variants")]
public IEnumerable<Variant> Variants { get; set; }
public IFormFile TEST { get; set; }
}
What was the error with the first code?
CodePudding user response:
I find my error. The mapping was not good. I checked in Postman before. Here is the solution if someone is interrested.
upload(prod: Product) {
let formData = new FormData();
formData.append("productName", prod.productName);
formData.append("productSku", prod.productSku);
for(let i=0;i<prod.variants.length;i ){
formData.append(`variants[${i}].variantName`, prod.variants[i].variantName);
formData.append(`variants[${i}].media.fileName`, prod.variants[i].media.fileName);
formData.append(`variants[${i}].media.mediaFile`, prod.variants[i].media.mediaFile);
}
this.http.post('https://localhost:7255/api/products', formData)
.subscribe(res => {
console.log(res);
alert('Uploaded Successfully.');
})
}