javascriptformsapifileapi

How could I check that if the file has a desirable extension when uploading a file in Javascript/FileApi


So the thing that's happening I am kind of stuck with the extensions of fileApi, I can't see to figure out how should I display the alert when the Upload file is not .pdf for example. I would really love some guidance. Thanks

Html

<form action="/Document" method="post" enctype="multipart/form-data">

        <div class="container">
            <div class="custom-file" style="margin-top: 25px; margin-bottom: 15px;">
                <input type="file" id="validatedCustomFile" name="document" required>
                <div style="color: red;"></div>
            </div>
            <div class="small">
                <ul>
                    <li>Maximum upload size is  / 1024) KB</li>
                </ul>
            </div>
            <div>

                <button type="submit" title="Next" class="btn btn-primary">Next</button>
                
            </div>
        </div>
    </form>

<script>
Js

    const InputFile = document.getElementById('validatedCustomFile');

    InputFile.addEventListener("change", function () {
        console.log(InputFile.files)
        for (const file of InputFile.files) {
            if (file.size > 1048576){
                alert(`${file.name} is to big! Max is 1024KB`);
            }
            if (file.type != '.pdf') {
                alert('This file type not allowed to be uploaded')
            }
        }    
    }
      
        )

</script>

Solution

  • here, you need to set mime type of file . Here, I have mention application/pdf instead of ".pdf"

        const InputFile = document.getElementById('validatedCustomFile');
    
        InputFile.addEventListener("change", function () {
            console.log(InputFile.files)
            for (const file of InputFile.files) {
               
                if (file.size > 1048576){
                    alert(`${file.name} is to big! Max is 1024KB`);
                }
                if (file.type != 'application/pdf') {
                    alert('This file type not allowed to be uploaded')
                }
             
            }    
        }
          
            )