1

I am accepting new files like this:

<input type="file" accept="image/x-png,image/gif,image/jpeg" required>

I do not currently have a converter in place, so webp images that are uploaded will not work when displayed on ios or Safari. To combat this, I added the jpg, png, and gif "accept" attribute.

However, if a user renames a webp as one of the accepted files, my file picker won't detect the mislabel, but it will still be a webp and therefore broken as described.

Is there a better way to check the file type using html or javascript?

akondelin
  • 131
  • 1
  • 6
  • 1
    Possible duplicate of [How to check file MIME type with javascript before upload?](https://stackoverflow.com/questions/18299806/how-to-check-file-mime-type-with-javascript-before-upload) (Hopefully you can extract a usable answer, it seems it's very similar.) – msanford Apr 20 '19 at 23:04
  • Yes, the answer provided by @lmiguelmh worked for me. I did not know to refer to this underlying file type as the MIME type. Thanks! – akondelin Apr 21 '19 at 00:10

1 Answers1

-1

// JS

    <script>
      var fileextension = "jpg|jpeg|gif|png|ico|bmp";

      function checkExtension(value)
      {
      if(value=="")return true;
      var re = new RegExp("^.+\.("+fileextension+")$","i");
      if(!re.test(value))
      {
      alert("File not allowed! \n" + value + "\n\nAllowed:    
      "+fileextension.replace(/\|/g,',')+" \n\n");
       return false;
       }

       return true;
       }
   </script>

//HTML

 <input type="file" name="image" onChange="checkExtension(this.value)">
Thorsten Wolske
  • 424
  • 4
  • 9
  • 2
    This would still allow the exploit, the problem is that people can rename image.webp to image.jpg, but the underlying file type doesn't change. Then users on safari can't see the file, even thought it's labeled as image.jpg, because its still actually webp. – akondelin Apr 20 '19 at 23:01
  • Please explain how your code works, and how the OP might fix it to make it suit their needs. – Jack Bashford Apr 20 '19 at 23:26
  • Don´t know if simply renaming will change the header from webp to jpg. You can convert images using php. https://www.php.net/manual/de/imagick.readimage.php – Thorsten Wolske Apr 20 '19 at 23:32
  • @JackBashford may i was misunderstanding the question at first. The code only will only check the file type of the choosen image. It does not check the mime type or image header. – Thorsten Wolske Apr 20 '19 at 23:39