Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect file extension with javascript FileReader

Tags:

I'm using javascript's FileReader and my customized function for reading an JPG-JPEG image, My problem is that how it's possible to detect the file extension through my code below and give error to user if the file is not JPG-JPEG:

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

    reader.onload = function (e) {
      alert('image has read completely!');
    }

    reader.readAsDataURL(input.files[0]);
  }
}
like image 387
Baya Avatar asked Aug 02 '14 14:08

Baya


People also ask

What does FileReader do in JavaScript?

The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.

How do I get the file extension of an input type file?

The full filename is first obtained by selecting the file input and getting its value property. This returns the filename as a string. By the help of split() method, we will split the filename into 2 parts. The first part will be the filename and the second part will be the extension of the file.

What is the file extension for JavaScript?

JavaScript files have the file extension .js.


2 Answers

You can try this, I changed your code as follows:

var fileTypes = ['jpg', 'jpeg', 'png', 'what', 'ever', 'you', 'want'];  //acceptable file types

function readURL(input) {
    if (input.files && input.files[0]) {
        var extension = input.files[0].name.split('.').pop().toLowerCase(),  //file extension from input file
            isSuccess = fileTypes.indexOf(extension) > -1;  //is extension in acceptable types

        if (isSuccess) { //yes
            var reader = new FileReader();
            reader.onload = function (e) {
                alert('image has read completely!');
            }

            reader.readAsDataURL(input.files[0]);
        }
        else { //no
            //warning
        }
    }
}
like image 158
Engin Üstün Avatar answered Oct 09 '22 20:10

Engin Üstün


There's not a direct interface to read the file extension. You have at least 2 options:

  • Use a regex to extract the extension from the filename
  • Use the content type of the file as your filter

For the extension method it'd be something like:

var extension = fileName.match(/\.[0-9a-z]+$/i);
like image 38
Dane O'Connor Avatar answered Oct 09 '22 21:10

Dane O'Connor