How to read a local text file?

前端 未结 20 2253
北恋
北恋 2020-11-21 05:28

I’m trying to write a simple text file reader by creating a function that takes in the file’s path and converts each line of text into a char array, but it’s not working.

相关标签:
20条回答
  • 2020-11-21 05:42

    Local AJAX calls in Chrome are not supported due to same-origin-policy.

    Error message on chrome is like this: "Cross origin requests are not supported for protocol schemes: http, data, chrome, chrome-extension, https."

    This means that chrome creates a virtual disk for every domain to keep the files served by the domain using http/https protocols. Any access to files outside this virtual disk are restricted under same origin policy. AJAX requests and responses happen on http/https, therefore wont work for local files.

    Firefox does not put such restriction, therefore your code will work happily on the Firefox. However there are workarounds for chrome too : see here.

    0 讨论(0)
  • 2020-11-21 05:43

    other example - my reader with FileReader class

    <html>
        <head>
            <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
            <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
            <script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
        </head>
        <body>
            <script>
                function PreviewText() {
                var oFReader = new FileReader();
                oFReader.readAsDataURL(document.getElementById("uploadText").files[0]);
                oFReader.onload = function (oFREvent) {
                    document.getElementById("uploadTextValue").value = oFREvent.target.result; 
                    document.getElementById("obj").data = oFREvent.target.result;
                };
            };
            jQuery(document).ready(function(){
                $('#viewSource').click(function ()
                {
                    var text = $('#uploadTextValue').val();
                    alert(text);
                    //here ajax
                });
            });
            </script>
            <object width="100%" height="400" data="" id="obj"></object>
            <div>
                <input type="hidden" id="uploadTextValue" name="uploadTextValue" value="" />
                <input id="uploadText" style="width:120px" type="file" size="10"  onchange="PreviewText();" />
            </div>
            <a href="#" id="viewSource">Source file</a>
        </body>
    </html>
    
    0 讨论(0)
  • 2020-11-21 05:47

    In order to read a local file text through JavaScript using chrome, the chrome browser should run with the argument --allow-file-access-from-files to allow JavaScript to access local file, then you can read it using XmlHttpRequest like the following:

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
       if (xmlhttp.readyState == 4) {
           var allText = xmlhttp.responseText;          
                }
            };
    xmlhttp.open("GET", file, false);
    xmlhttp.send(null);
    
    0 讨论(0)
  • 2020-11-21 05:49

    This might help,

        var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                alert(xmlhttp.responseText);
            }
        }
    
        xmlhttp.open("GET", "sample.txt", true);
        xmlhttp.send();
    
    0 讨论(0)
  • 2020-11-21 05:50

    Using Fetch and async function

    const logFileText = async file => {
        const response = await fetch(file)
        const text = await response.text()
        console.log(text)
    }
    
    logFileText('file.txt')
    
    0 讨论(0)
  • 2020-11-21 05:52
    function readTextFile(file) {
        var rawFile = new XMLHttpRequest(); // XMLHttpRequest (often abbreviated as XHR) is a browser object accessible in JavaScript that provides data in XML, JSON, but also HTML format, or even a simple text using HTTP requests.
        rawFile.open("GET", file, false); // open with method GET the file with the link file ,  false (synchronous)
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4) // readyState = 4: request finished and response is ready
            {
                if(rawFile.status === 200) // status 200: "OK"
                {
                    var allText = rawFile.responseText; //  Returns the response data as a string
                    console.log(allText); // display text on the console
                }
            }
        }
        rawFile.send(null); //Sends the request to the server Used for GET requests with param null
    }
    
    readTextFile("text.txt"); //<= Call function ===== don't need "file:///..." just the path 
    

    - read file text from javascript
    - Console log text from file using javascript
    - Google chrome and mozilla firefox

    in my case i have this structure of files :

    the console.log result :

    0 讨论(0)
提交回复
热议问题