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

随声附和 提交于 2019-12-12 11:24:18

问题


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();
    }
})

回答1:


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">


来源:https://stackoverflow.com/questions/36038235/is-it-possible-to-load-a-specific-file-type-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!