You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core项目中JavaScript传递IFormFile至控制器为null的问题

.NET Core项目中JS传递文件至控制器时为null的问题

我正在开发一个.NET Core项目,尝试通过JavaScript获取表单数据来创建帖子。其中字符串类型的Content、int数组类型的SelectedIds可正常传递至控制器,但File类型的ContentPhoto在控制器端接收时始终为null——尽管能通过console.log()正常打印该文件,但其传递到控制器后会变为null。

HTML代码

<form class="post-text ms-3 w-100" asp-action="PostCreate" asp-controller="Home" enctype="multipart/form-data">
    <div class="d-flex align-items-center">
        <div class="user-img">
            <img src="~/front/assets/images/user/1.jpg" alt="userimg" class="avatar-60 rounded-circle img-fluid">
        </div>

        <input type="text" id="ContentText"  class="form-control rounded" placeholder="Write something here..." style="border:none;">
    </div>
    <hr>
    <div class="col-lg-12">
        @foreach (var tag in ViewBag.Tags as List<GetTagsQueryResult>)
        {
            <button type="button" class="tagButton" data-tag-id="@tag.Id" id="@tag.Id">@tag.Name</button>
        }
    </div>
    <hr>

    <div class="photonewDiv" id="photonewDiv" style="display: none;align-items: center;">
        <img id="uploadedImage" src="" alt="yourPost" class="img-fluid" style="display: none;border-radius: .75rem !important;max-height:95% !important;max-width:95%">
        <hr>
    </div>

    <ul class="d-flex flex-wrap align-items-center list-inline m-0 p-0">

        <li class="col-md-6 mb-3">
            <div class="bg-soft-primary rounded p-2 pointer me-3" id="fileUploadDiv">
                <a href="#">Photo/Video</a>
                <img src="~/front/assets/images/small/07.png" alt="icon" class="img-fluid">
            </div>
        </li>

        <input type="file" name="ContentPhoto" id="fileInput" style="display: none;">

        <li class="col-md-6 mb-3">
            <div class="bg-soft-primary rounded p-2 pointer me-3"><a href="#"></a><img src="~/front/assets/images/small/08.png" alt="icon" class="img-fluid"> Tag Friend</div>
        </li>
        <li class="col-md-6 mb-3">
            <div class="bg-soft-primary rounded p-2 pointer me-3"><a href="#"></a><img src="~/front/assets/images/small/09.png" alt="icon" class="img-fluid"> Feeling/Activity</div>
        </li>
        <li class="col-md-6 mb-3">
            <div class="bg-soft-primary rounded p-2 pointer me-3"><a href="#"></a><img src="~/front/assets/images/small/12.png" alt="icon" class="img-fluid"> Gif</div>
        </li>
    </ul>
    <button type="button" onclick="send()" class="btn btn-primary d-block w-100 mt-3">Post</button>
</form>

JavaScript(FormData方式)

function send() {
  var content = document.getElementById("ContentText").value;

  var fileInput = document.getElementById("fileInput");
  var selectedFile = fileInput.files[0];

  var selectedButtons = document.querySelectorAll(".tagButton.selected");
  var selectedButtonsIds = [];
  for (var i = 0; i < selectedButtons.length; i++) {
    selectedButtonsIds.push(parseInt(selectedButtons[i].getAttribute("id")));
  }

  console.log(content);
  console.log(selectedFile);
  console.log(selectedButtonsIds);

  var formData = new FormData();
  formData.append("Content", content);
  formData.append("ContentPhoto", selectedFile);
  formData.append("PostTagsId", selectedButtonsIds);

  fetch("/Home/PostCreate2", {
    method: "POST",
    processData: false,
    contentType: false,
    headers: {
      "Content-Type": "multipart/form-data",
    },
    body: formData,
  })
    .then((response) => response.json())
    .then((data) => {
      if (data === true) {
        toastr.success("Post Create Process Is Success!");
      } else {
        toastr.error("Error! " + data);
      }
    });
}

控制器(FormData对应)

[HttpPost]
public async Task<IActionResult> PostCreate2(string Content, IFormFile? ContentPhoto, int[] PostTagsId)
{
    return Json(false);
}

我尝试用模型替代FormData传递,问题依然存在:

JavaScript(模型方式)

function send() {
  var content = document.getElementById("ContentText").value;
  var selectedFile = document.getElementById("fileInput").files[0];
  var selectedButtons = document.querySelectorAll(".tagButton.selected");
  var selectedButtonsIds = [];
  for (var i = 0; i < selectedButtons.length; i++) {
    selectedButtonsIds.push(
      parseInt(selectedButtons[i].getAttribute("data-tag-id")),
    );
  }

  var model = {
    Content: content,
    ContentPhoto: selectedFile,
    PostTagsId: selectedButtonsIds,
  };

  console.log(model);

  fetch("/Home/PostCreate2", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(model),
  })
    .then((response) => response.json())
    .then((data) => {
      if (data === true) {
        toastr.success("Post Create Process Is Success!");
      } else {
        toastr.error("Error! " + data);
      }
    });
}

控制器(模型对应)

[HttpPost]
public async Task<IActionResult> PostCreate2([FromBody] CreatePostCommand model)
{
    // 使用模型数据进行操作
    return Json(false);
}

内容的提问来源于stack exchange,提问作者ENES BİRİCİK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 02:07:04