我无法使用 JavaScript 导入 IFormFile 对象

问题描述 投票:0回答:1

我正在使用 .Net Core 开发一个项目,我正在尝试使用 JavaScript 获取表单上的数据以创建帖子。虽然 Content(字符串表达式)和 SelectedIds(int 数组)通常会到达,但我作为文件接收的 ContentPhoto 在接收时会给控制器端带来问题(变为 null)。

console.log()
虽然可以使用 () 表达式将其写入控制台,但它会作为 null 传输到控制器。

以下是我的设计代码:

<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:

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);
      }
    });
}

控制器:(只是为了检查数据是否到来。)

[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)
{
    // Model verilerini kullanarak işlemler yapabilirsiniz
    return Json(false);
}
javascript asp.net-mvc asp.net-core
1个回答
0
投票

您必须检查代码中的一些要点:

1) 当使用

FormData
提交
fetch
对象时,不要手动设置
Content-Type
header,让浏览器处理。

2)当您将数组附加到

FormData
时,您需要使用
[]
来确保服务器将其识别为值数组。

3)JSON无法处理二进制数据和日期类型,因此无法以JSON发送文件(二进制数据)

这是更新后的代码:

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")));
    }

    var formData = new FormData();
    formData.append("Content", content);
    if (selectedFile) {
        formData.append("ContentPhoto", selectedFile);
    }
    selectedButtonsIds.forEach(id => formData.append("PostTagsId", id));

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

只需确保参数名称与您在

FormData
中使用的键匹配,并在控制器端检查操作方法签名与 FormData 中使用的键匹配。

© www.soinside.com 2019 - 2024. All rights reserved.