Reading file contents on the client-side in javascript in various browsers

后端 未结 4 892
南旧
南旧 2020-11-22 06:45

I\'m attempting to provide a script-only solution for reading the contents of a file on a client machine through a browser.

I have a solution that works with Firefox

4条回答
  •  太阳男子
    2020-11-22 07:17

    In order to read a file chosen by the user, using a file open dialog, you can use the tag. You can find information on it from MSDN. When the file is chosen you can use the FileReader API to read the contents.

    function onFileLoad(elementId, event) {
        document.getElementById(elementId).innerText = event.target.result;
    }
    
    function onChooseFile(event, onLoadFileHandler) {
        if (typeof window.FileReader !== 'function')
            throw ("The file API isn't supported on this browser.");
        let input = event.target;
        if (!input)
            throw ("The browser does not properly implement the event object");
        if (!input.files)
            throw ("This browser does not support the `files` property of the file input.");
        if (!input.files[0])
            return undefined;
        let file = input.files[0];
        let fr = new FileReader();
        fr.onload = onLoadFileHandler;
        fr.readAsText(file);
    }
    
    

提交回复
热议问题