Javascript FileReader onload not firing

前端 未结 4 835
故里飘歌
故里飘歌 2020-12-31 03:02

I haven\'t used JavaScript in a while and I can\'t seem to read a text file and display the contents.

I\'ve tried onload as well as onloadend

4条回答
  •  悲&欢浪女
    2020-12-31 03:42

    You can't grab a local file like that for security reasons.

    Another underlying problem is that readAsText (and all the read functions) need the file's content and not its file path/name. You can grab this from the files collection of the input type="file" element. Here is how your code could work:

    function readFile(file) {                                                       
        var reader = new FileReader();
        reader.onload = readSuccess;                                            
        function readSuccess(evt) { 
            var field = document.getElementById('main');                        
            field.innerHTML = evt.target.result;                                
        };
        reader.readAsText(file);                                              
    } 
    
    document.getElementById('selectedFile').onchange = function(e) {
        readFile(e.srcElement.files[0]);
    };
    

    Here is the jsfiddle: http://jsfiddle.net/fstreamz/ngXBV/1/

    Note: this code not work in safari browser

提交回复
热议问题