Check file extension and alert user if isn’t image file

I need help to add some line of code to check is file is image, to check extension. This is my code that I use for indicate progress of uploading images. I do that in php and user can’t upload any file except .jpg .jpeg .gif and .png but he doesn’t get a message that file isn’t uploaded. When I add javascript code for progress upload, my php message taht i create doesn’t display anymore.

This is my javascript
upload.js file code:

 var handleUpload = function(event) {
    event.preventDefault();
    event.stopPropagation();

    var fileInput = document.getElementById('image_id');

    var data = new FormData();

    data.append('javascript', true);

        if(fileInput.files[0].size > 1050000) {
        document.getElementById("image_id").innerHTML = "Image too big (max 1Mb)";
        alert('Fotografija koju želite dodati je veća od 1Mb!');
        window.location="upload_images.php"
        return false;
        }

    for (var i =0; i < fileInput.files.length; ++i) {
        data.append('image', fileInput.files[i]);
    }

    var request = new XMLHttpRequest();

    request.upload.addEventListener('progress', function(event) {
        if (event.lengthComputable) {
            var percent = event.loaded / event.total;
            var progress = document.getElementById('upload_progress');

            while (progress.hasChildNodes()) {
                progress.removeChild(progress.firstChild);
            }

            progress.appendChild(document.createTextNode(Math.round(percent * 100) + ' %'));
        }
    });

    request.upload.addEventListener('load', function(event) {
        document.getElementById('upload_progress').style.display = 'none';
    });

    request.upload.addEventListener('error', function(event) {
        alert('Dodavanje slika nije bilo uspješno! Pokušajte ponovo.');
    });

    request.addEventListener('readystatechange', function(event) {

        if (this.readyState == 4) {
            if(this.status == 200) {
                var links = document.getElementById('uploaded');

                window.location="upload_images.php?success"
                console.log(this.response); 
            } else {
                console.log('Server replied with HTTP status ' + this.status);
            }
        }

    });

    request.open('POST', 'upload_images.php');
    request.setRequestHeader('Cache-Control', 'no-cache');

    document.getElementById('upload_progress').style.display = 'block';

    request.send(data);
}

window.addEventListener('load', function(event) {
    var submit = document.getElementById('submit');
    submit.addEventListener('click', handleUpload);

});

And this is my form for uploading file:

<div id="uploaded">

</div>
<div>
<form action="" method="post" enctype="multipart/form-data">
<input name="image" id="image_id" type="file" size="25" value="Odaberi sliku" />
<input type="submit" id="submit" value="Dodaj Foto"/>
</form>
</div>
<div class="upload_progress" id="upload_progress"></div>

I need in that javascript code also to check is file is image. To allow jpg, jpeg, png and gif extensions and block others. To alert user if he trying to upload other kind of file.

Read More:   javascript remove "disabled" attribute from html input

if (!fileInput.files[0].name.match(/\.(jpg|jpeg|png|gif)$/i))
    alert('not an image');

for Vue.js

if (filename.match(/.(jpg|jpeg)$/i)){
                     $('#modalimage').modal('show')    
                     vm.downloadimage = result.data
                 }else{
                  const a = document.createElement('a')
                  a.setAttribute('href', result.data)
                  a.dispatchEvent(new MouseEvent("click", {'view': window, 'bubbles': 
true, 'cancelable': true}))
                 }

style you give class name-jsp

"Choose file",input:true,icon:true,classButton:"btn",classInput:"input-large name-jsp"

at your jsp or html you give id=”cekJpg”(at click upload file not choose file)

<input id="cekJpg" type="submit" class="btn btn-primary" value="Upload image"> 

at javascript

//if click button upload image with id="cekJpg"
$("#cekJpg").on('click', function (e) {
    //get your format file
    var nameImage = $(".name-jsp").val();
    //cek format name with jpg or jpeg
    if(nameImage.match(/jpg.*/)||nameImage.match(/jpeg.*/)){
        //if format is same run form
    }else{
        //if with e.preventDefault not run form
        e.preventDefault();
        //give alert format file is wrong
        window.alert("file format is not appropriate");
    }
});

Other accepted answers here were true at their time, but are decade old and are not perfect any more. For now use the below as the latest 2022 solution:

if (!fileInput.files[0].name.match(/\.(jpg|jpeg|png|gif)$/i))
alert(‘not an image’);

Longer Explanation:

For e.g: ‘name.ijpg’ is not image, but monkeyinsight’s accepted old answer still return true. While the latest above solution works perfectly. See below:

console.log('name.ijpg'.match(/.(jpg|jpeg|png|gif)$/i));   // Old Solution
console.log('name.ijpg'.match(/\.(jpg|jpeg|png|gif)$/i));  // Correct Solution
console.log('name.jpg'.match(/\.(jpg|jpeg|png|gif)$/i));   // Correct Solution


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts