.NET Core中使用Ajax上传多张图片仅传递单个文件的问题
解决多文件上传仅首个文件传递至控制器的问题
问题根源
当前代码逻辑是遍历页面中所有type='file'的输入元素,但如果你的场景是单个文件输入框选择多个文件,代码只会处理第一个文件输入框的首个文件,其余选中的文件不会被添加到FormData中。另外,若文件输入框未添加multiple属性,本身就仅支持选择单个文件。
修复步骤
- 修改文件输入框属性
确保文件输入框允许选择多个文件,添加multiple属性:
<input type="file" name="fileInputs" multiple />
- 调整JavaScript代码逻辑
将遍历多个文件输入框的逻辑,改为遍历单个输入框内的所有选中文件:
$("#photoSubmit").click(function () { var formData = new FormData(); var imageDescriptions = []; // 收集所有描述文本 $("#image-list .list-images .list-itm").each(function () { var description = $(this).find("textarea").val(); imageDescriptions.push(description); }); // 获取单个文件输入框,并遍历其中所有选中的文件 var fileInput = $("#frmUpload input[type='file']")[0]; if (fileInput.files.length > 0) { for (var index = 0; index < fileInput.files.length; index++) { var description = imageDescriptions[index] || ""; formData.append("Photos[" + index + "].Image", fileInput.files[index]); formData.append("Photos[" + index + "].Description", description); formData.append("Photos[" + index + "].UserId", $("#u-id").val()); } } // 调试输出FormData内容(可选) formData.forEach(function (value, key) { console.log(key, value); }); $.ajax({ async: true, type: 'post', data: formData, contentType: false, processData: false, dataType: "html", url: "/User/Photo/AddPhoto", success: function (partialView) { // 处理成功响应 }, error: function (partialView) { // 处理错误 } }); });
后端接收验证(以ASP.NET为例)
确保后端模型和接口正确支持多文件绑定:
public class PhotoModel { public IFormFile Image { get; set; } public string Description { get; set; } public int UserId { get; set; } } [HttpPost] public IActionResult AddPhoto(List<PhotoModel> Photos) { // 处理上传的文件集合 return PartialView(); }
内容的提问来源于stack exchange,提问作者robert_rg
相关产品推荐
相关产品推荐

