-1

I have this function to preview an image before uploading:

    function readURL(input) {

if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function (e) {
         var if_alternative = true;

       //if image is either jpeg or png {
        $('#preview_image').attr('src', e.target.result);
       //} else { error

        $('#product_images').css("visibility","hidden");
        $('#fileSelector').css("visibility","hidden");
        $('#delete_image_1').removeClass("visibility_hidden");
    }
    reader.readAsDataURL(input.files[0]);
  } 
 }

$("#product_images").change(function(){
readURL(this);
});

I think the commented code speaks for itself. I would like to preview the image only when it is either a "JPEG" or a "PNG" - file. Can anybody help out? I have already tried several statements, but nothing worked. Thanks!

Frank
  • 614
  • 1
  • 8
  • 31

1 Answers1

0

Use below Code - Use lastIndexOf() of JavaScript function.

var fname =  input.files[0];
var FileExtension =  fname.substr((~-fname.lastIndexOf(".") >>> 0) + 2)

if(FileExtension.toLowerCase() == "jpeg" || FileExtension.toLowerCase() == "png")
{
       // do your stuff here
}
else
{
     alert('Invalid File');
}
prog1011
  • 3,425
  • 3
  • 30
  • 57