更改“未选择文件”。文件上传返回时

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

我有以下用于加载文件的代码:

<form enctype="multipart/form-data" asp-action="UploadFile" asp-controller="ControllerX" method="post">
    <dl>      
        <dd>
            <input name="file" type="file">
        </dd>
    </dl>
    <input class="btn btn-primary" type="submit" value="Upload" />
</form>

enter image description here

当我选择要加载的文件时,它会写入文件名来代替“未选择文件”,这很棒。按下上传按钮后,文件将被加载并返回到此页面,并且现在再次显示“未选择文件”。如何将其更改为“文件 XXXX 已成功加载”

谢谢!

html
1个回答
0
投票

我相信这就是您正在寻找的 ->

function displayFileName() {
  const fileInput = document.getElementById("fileInput");
  const fileStatus = document.getElementById("fileStatus");

  if (fileInput.files.length > 0) {
    fileStatus.textContent = `Selected file: ${fileInput.files[0].name}`;
  } else {
    fileStatus.textContent = "No file selected";
  }
}


document.getElementById("uploadForm").addEventListener("submit", function(event) {
  event.preventDefault();
  const fileInput = document.getElementById("fileInput");

  if (fileInput.files.length > 0) {
    document.getElementById("fileStatus").textContent = `File ${fileInput.files[0].name} has been successfully loaded`;
    setTimeout(() => this.submit(), 1000);
  }
});
<form enctype="multipart/form-data" asp-action="UploadFile" asp-controller="ControllerX" method="post" id="uploadForm">
  <div>
    <div>
      <input id="fileInput" name="file" type="file" onchange="displayFileName()">
      <p id="fileStatus">No file selected</p>
    </div>
  </div>
  <input class="btn btn-primary" type="submit" value="Upload" />
</form>

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