例如,我有這個代碼,它將資料發送到 asp.net core 6 web api 控制器。
const formData = new FormData();
formData.append("Id", 1);
formData.append("PhotoNames", ["name1", "name2", "name3"]);
formData.append("Photos", [file1, file2, file3)];
axios.post("/api/MyController", formData);
file1, file2, file3是照片,我收到了表格<input type="file"/>。
我處理了相同的請求,但沒有陣列,通過在以下代碼中使用MyController.cs:
public class Item
{
public int Id { get; set; }
public string PhotoName{ get; set; }
public IFormFile Photo { get; set; }
}
[HttpPost]
public IActionResult Post([FromForm] ImageModel file)
{
//Using all the data from the request here
}
請求看起來像:
const formData = new FormData();
formData.append("Id", 1);
formData.append("PhotoName", "name1");
formData.append("Photo", file1);
axios.post("/api/MyController", formData);
如何處理包含陣列的發布請求?我需要使用什么樣的類和函式MyController.cs?
uj5u.com熱心網友回復:
在編碼之前,您需要了解以下知識:
formData 鍵名稱應與模型屬性名稱匹配。
模型屬性應該是串列或陣列。
formData.append("PhotoNames", ["name1", "name2", "name3"]);通過 FormData 而不是串列項將一項發布到串列中。你需要像下面這樣的帖子:formData.append("PhotoName", "name1"); formData.append("PhotoName", "name2"); formData.append("PhotoName", "name3");
這是您可以遵循的完整作業演示:
模型:
public class ImageModel
{
public int Id { get; set; }
public string[] PhotoName { get; set; }
public IFormFile[] Photo { get; set; }
}
看法:
<input type="file" multiple name="FileList" />
@section Scripts
{
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
$("input[name='FileList']").change(function () {
const formData = new FormData();
$("input[name='FileList']").each(function () {
var ReadyToUpload = $(this)[0].files;
if (ReadyToUpload.length > 0) {
$.each(ReadyToUpload, function (i, file) {
formData.append("Photo", file);
});
}
});
formData.append("Id", 1);
formData.append("PhotoName", "name1");
formData.append("PhotoName", "name2");
formData.append("PhotoName", "name3");
//formData.append("Photos", [file1, file2, file3)];
axios.post("https://localhost:44397/api/WeatherForecast", formData);
})
</script>
}
介面:
[ApiController]
[Route("api/[controller]")]
public class WeatherForecastController : ControllerBase
{
[HttpPost]
public void Post([FromForm] ImageModel file)
{
//Using all the data from the request here
}
}
結果:

uj5u.com熱心網友回復:
嘗試使 PhotoNames 和 Photos 表單資料成為一個陣列
const formData = new FormData();
formData.append("Id", 1);
formData.append("PhotoNames[]", ["name1", "name2", "name3"]);
formData.append("Photos[]", [file1, file2, file3)];
axios.post("/api/MyController", formData);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/366922.html
標籤:javascript C# 数组 asp.net核心 公理
上一篇:ASP.NETCoreWebAPI-如何將屬性組合作為原始資料存盤到另一個模型的單列中
下一篇:部分字串匹配的SQL連接
