【问题标题】:Asp.net Core-choose and Validate excel file before uploading using javascript or C#?Asp.net Core-在使用 javascript 或 C# 上传之前选择和验证 excel 文件?
【发布时间】:2022-01-20 21:48:57
【问题描述】:

1-如何只选择 Excel 格式的文件?

2-如何在 JavaScript 和 C# 中验证文件格式?

我在 Asp.Net Core 3.1 中使用 EPPlus 插件?

HTML:

<form id="SelectExcelForm" method="post">
  <div class="form-group">
    <div class="form-line">
      <input type="file" name="ExcelFile" class="form-control" />
      <span class="text text-danger">True Format : xlsx </span>
    </div>
  </div>
  <div class="modal-footer">
    <button type="button" onclick="return ValidateForm()" class="btn btn-info waves-effect">Save</button>
  </div>
</form>

【问题讨论】:

标签: javascript asp.net-core


【解决方案1】:

如果要在C#代码中验证文件格式,可以使用以下代码:

<input type="file" name="ExcelFile" class="form-control" accept=".xls,.xlsx" />

这样,选择框中只能看到Excel格式的文件。

当你想使用 JS 进行验证时,你可以使用这些代码:

<input type="file" name="ExcelFile" class="form-control" onchange="fileChange(this)" />

    <script>
        function fileChange(target) {
            var name=target.value;
            var fileName = name.substring(name.lastIndexOf(".")+1).toLowerCase();
            if(fileName !="xls" && fileName !="xlsx"){
                alert("please upload file in Excel forma!");
                target.value="";
                return false;   
            }
        }

    </script>

这样,你可以在选择框中看到所有格式的文件,但是当你选择其他格式的文件时,会上传失败。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-03
    • 2015-01-04
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    相关资源
    最近更新 更多