vanilla javascript 客户端(我尝试使用 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 控制器 API
[EnableCors("policy")]
[HttpPost]
[Route("senderror")]
public async Task<IActionResult> HandleError([FromForm]ErrorModel error)
{
return Ok();
}
浏览器调试器显示模型包含值,但到达控制器的数据为空。
您正在错误对象内的 formdata 中以及您已应用的 api 上发送文件
[FromForm]
因此服务器期望表单中的数据,并且您正在发送包含表单数据的对象。我认为如果你将所有数据附加到 formdata 中,那么它会起作用,因为你的 api 期望 formdata 中的数据。像这样更改它
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",
})
})
你必须设置
"Content-Type": "multipart/form-data",