Search code examples
javascriptimagefileapi

Check file type before uploading


I am developing plugin to preview and crop an image before uploading. I faced one interesting bug.

I am validating file extension to determinate if it is an image. But one of my user just change text file extension in Total Commander and try to upload it.

This is part of code:

reader.onload = function(e) {
  if(e.target.result.indexOf("data:image")) { //check if file have an image extension
    return false;
  }   
  var image = new Image();
  image.src = e.target.result;
  image.onload = function() {
    // Never have been triggered if user tries to upload text file with *.jpg     extension
  }
}

How can I check if file is an image and show some alert otherwise?


Solution

  • if relying on file extension is not good enough for you, it is possible to inspect the first bytes of a file and check against some common headers.

    these are the first bytes of

    • JPEG: FF D8
    • GIF: 47 49 46
    • PNG: xx 80 78 71

    see: http://www.mikekunz.com/image_file_header.html & http://www.libpng.org/pub/png/book/chapter08.html#png.ch08.div.2

    you can read the bytes using the File API: HTML5 File API read as text and binary

    bare in mind that a client side javascript check can still be modified in the client. so that you would need to re-check on the server. this is why probably just checking the extension on the client might be enough. a user that actively tries to upload a non-image might circumvent both client checks.