vanilla javascript client (I tried doing it with axios/ajax/fetch)
const myForm = document.getElementById("myForm");
myForm.addEventListener("submit", (e) => {
debugger;
var name = document.getElementById("errorInput").value;
var description = document.getElementById("errorDescriptionInput").value;
var date = document.getElementById("errorDateInput").value;
var mail = document.getElementById("senderEmailInput").value;
var file = document.getElementById('fileInput').files[0];
var formData = new FormData();
formData.append('fileInput', file);
const error = {
ErrorName: name,
ErrorDescription: description,
ErrorSubmittedDate: date,
SenderEmail: mail,
Documents: formData,
}
axios.post("https://localhost:44310/api/Error/senderror","sendFile", error, {
"Content-Type": "multipart/form-data",
"Content-Type": "application/json",
})
})
.net controller API
[EnableCors("policy")]
[HttpPost]
[Route("senderror")]
public async Task<IActionResult> HandleError([FromForm]ErrorModel error)
{
return Ok();
}
Browser debugger shows that the model contains the values, but the data that comes to the controller is null.
You are sending your file in formdata inside your error object and on api you have applied
[FromForm]
so server expect the data in form and you are sending an object containing formdata. i think if you append all data in formdata then it would work coz you api is expecting data in formdata.change it like this
const myForm = document.getElementById("myForm");
myForm.addEventListener("submit", (e) => {
debugger;
var name = document.getElementById("errorInput").value;
var description = document.getElementById("errorDescriptionInput").value;
var date = document.getElementById("errorDateInput").value;
var mail = document.getElementById("senderEmailInput").value;
var file = document.getElementById('fileInput').files[0];
var formData = new FormData();
error.append('ErrorName', name);
error.append('ErrorDescription', description);
error.append('ErrorSubmittedDate', date);
error.append('SenderEmail', file);
error.append('Documents', mail);
axios.post("https://localhost:44310/api/Error/senderror","sendFile", error, {
"Content-Type": "multipart/form-data",
})
})
you have to set
"Content-Type": "multipart/form-data",