Hello.
In the form I need to upload a CSV file to the site.
How to prevent users from loading files of other formats into this form?

accept="text/csv" 

Or is some other MME type correct for this format? Or is it possible to do something with javascript?
Thank.

UPD There is such a code

 var filesExt = ['csv']; $('input[type=file]').change(function(){ var parts = $(this).val().split('.'); if(filesExt.join().search(parts[parts.length - 1]) == -1){ alert('Не совпадает формат файла'); } }); 

Tell me, please, how, after the alert, add more and clear this file field?

  • about the first point of the question: just accept = "csv" - Mae
  • @Mae does not help, any files are loaded, therefore I am looking for a javascript - Alexander Vladimirovich

2 answers 2

To explicitly limit the allowed file types, you need to add a filter to the displayed files in the html element: accept=".csv"
This filter can be bypassed if you select the "All files" form in the filter. To prevent this, add your code:

 var re = /(?:\.([^.]+))?$/; var fileExt = 'csv'; $('input[type=file]').change(function(){ if (fileExt.indexOf(re.exec($('.file-for-import')[0].files[0].name)[1]) < 0){ alert('Не совпадает формат файла'); $('.file-for-import')[0].value = null; } }); 

Link to a working example: https://jsfiddle.net/cbamdqt1/5/

    It works, checks if the file csv, makes the file. HTML:

     <form> <input type="text"> <input type="file"> </form> <button id="bt">RESET FILE</button> 

    Javascript

      var res = document.querySelector('input[type=file]'); res.addEventListener("change", function(){ var type = this.files[0].name.split(".").pop(); if(type != "csv") { alert("wrong file format"); } }) document.getElementById('bt').addEventListener("click", function(){ var frm = document.querySelector('input[type=file]'); frm.value = ""; })