user4720622
user4720622

Reputation:

Is it possible to load a specific file type using Javascript?

I have a function that is loading a user selected file using the Javascript File API, but I want to limit the type of file that can be loaded. Is this possible and how do I go about doing it? So for example, I only want the user to be able to load a DAT file. Here's my function loading the file.

function readFile(file){
    var reader = new FileReader();
    var holder;
    var holderArray = [];
    var fileArray = [];
    reader.readAsText(file, "UTF-8");
    reader.onload = function(){
        file = reader.result;
        file = file.split(/\s+/g);
        formatFile(holderArray, 3, holder, file, fileArray);
        for(var i = 0; i < 2; i++){
            formatFile(holderArray, 1, holder, file, fileArray);
        }
        for(var i = 0; i < 2; i++){
            formatFile(holderArray, 2, holder, file, fileArray);
        }
        var meh = file.length / fileArray.length;
        for(var i = 0; i < meh; i++){
            formatFile(holderArray, 5, holder, file, fileArray);
        }
        fileArray.pop();

        plume = new Plume(fileArray[0], fileArray[4], fileArray[3]);
        $("#eventDate").val(plume.dateTime);
        $("#eventLat").val(plume.startLat);
        $("#eventLon").val(plume.startLong);
        $("#eventDictionary").val(plume.dict);
        $("#eventSymbol").val(plume.symbol);

        fileArray = fileArray.splice(5);
        plume.graphic = fileArray;
    }
}

$("#load").on("click", function(){
    $("#eventNameInput").val("");
    var selectedFile = $("#selectedFile");
    selectedFile = selectedFile[0].files[0];
    if(selectedFile){
        readFile(selectedFile);
        $("#fileDetails").show();
    }
})

Upvotes: 4

Views: 1393

Answers (1)

S. Nadezhnyy
S. Nadezhnyy

Reputation: 582

Sure. You can declare MIME type in "accept" attribute For example this input will upload images :

<input type="file" name="img" accept="image/*">

for .dat you can do this (.dat is unknown MIME type):

<input type="file" name="img" accept=".dat">

Upvotes: 4

Related Questions