1

1-How can I select only files in Excel format? enter image description here

2-How do I validate the file format in both JavaScript and C #?

I Use The EPPlus Plugin in Asp.Net Core 3.1?

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>
MarioG8
  • 5,122
  • 4
  • 13
  • 29
sunboy_sunboy
  • 225
  • 2
  • 14
  • For client-side validation: https://stackoverflow.com/a/4329008/6310593, server side you can check the extension and file header bytes. – MaartenDev Dec 18 '21 at 13:17

1 Answers1

1

if you want to validate the file format in C# code , You can use the following code:

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

In this way , You can only see files in Excel format in the selection box.

When you want to use JS to validate , you can use these code:

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

In this way , You can see files in all formats in the selection box , but when you select files in other format , It will fail to upload.

enter image description here

Xinran Shen
  • 8,416
  • 2
  • 3
  • 12