Funk Forty Niner
Funk Forty Niner

Reputation: 74217

Validating file extensions from an array

I have searched the Web and SO to figure this one out by myself with many different ways, but with no success.

I would like to show a message if the file extension is accepted or not, in the same fashion as the "outpush.push" statements.

This would need to be taken from an ARRAY of accepted file extensions such as JPG, PNG, GIF and detect if the file extension is uppercase and accept it (convert it to lowercase).

Here is my script. Am wondering how and where in the script could I implement such a feature?

function handleFileSelect(evt) {

    var files = evt.target.files; // FileList object
    var max_size = 5120; // Max file size

    var output = [];
    for (var i = 0, f; f = files[i]; i++) {

        output.push('<li><strong><font size="3" color="FFFFFF">FILE: ', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
            f.size, ' bytes, last modified: ',
            f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
            '</font></li>');

        if(f.size > max_size) {

            output.push('<font size="5" color="FFFF00"><b>ERROR!! Sorry, but the file that you selected is too large. Please upload a file that is no larger than ' + max_size + ' KB.');
        }

        if(f.size < max_size) {
            output.push('<font size="5" color="FFFF00"><b>FILE SIZE OK. CLICK TO SEND button below.</font>');

            output.push('<font size="5" color="FFFFFF"><hr><b>IMPORTANT: Do not close this window. Wait till you see the next page when finished uploading your file.</font>');

            document.getElementById("myButton").style.display="all";
        }

    }

    document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
}

document.getElementById('files').addEventListener('change', handleFileSelect, false);

Upvotes: 3

Views: 6739

Answers (3)

Jeff B
Jeff B

Reputation: 30099

There are a couple of issues with your code.

1) You should use an if-else, instead of multiple if statements:

if (f.size > max_size) {
    // ...
} else {
    // ...
}

2) all is not a valid value for display, use block or inline:

document.getElementById("myButton").style.display = "block";

3) You are using outdated <font> tags. Instead, use styles and CSS. In your case, I would use classes, one for a msg, plus additional classes for error, important, and ok.

4) To do the array check, just use indexOf():

var extensions = ["jpg", "jpeg", "txt", "png"];  // Globally defined

...

// Get extension and make it lowercase
// This uses a regex replace to remove everything up to 
// and including the last dot
var extension = f.name.replace(/.*\./, '').toLowerCase();

if (extensions.indexOf(extension) < 0) {  // Wasn't found
    output.push('<li class="msg error">ERROR!! Sorry, but the file that you selected is not a valid file type.  Valid types are: ', valid, '</li>');
} else ...

Demo: http://jsfiddle.net/jtbowden/L2Gps/

Upvotes: 9

Andy Jones
Andy Jones

Reputation: 6275

You can try one of two approaches - either try a grab the extension and match it against an array of allowed extensions, or a regular expression.

var accepted_types = ['jpg', 'gif', 'png'];
if (accepted_types.indexOf(f.ext) > 0) {
  output.push(...);
}

As for the jQuery - you might consider the following for building your HTML

var file_list = $("<ul></ul>");
for (var i = 0, f; f = files[i]; i++) {
  // work goes here, simply append the list elements into file_list
  file_list.append($("<li>" ... "</li>"));
}

// to append your new list to id="list"
$("#list").append(file_list);
// or to replace the html with your new html
$("#list").html(file_list.html());

Upvotes: 0

RenegadeMatrix
RenegadeMatrix

Reputation: 141

You can have the array as something like this:

var file_types = {'jpg', 'png', 'gif'};

and then do something like this in your for-loop

if ($.inArray(f.ext, file_types) == -1) {
output.push('<font size="5" color="FFFF00"><b>ERROR!! Incorrect file type! Accepted file types are : jpg, png, gif</b></font>');
}

More reading about inArray().

Upvotes: 2

Related Questions