jQuery: read text file from file system

前端 未结 10 2442
再見小時候
再見小時候 2020-11-30 10:09

I am trying to read a text file using jquery, like this:

// LOAD file and split line by line and append divs
$.get(\'myFile.txt\', function(data) {    
    v         


        
相关标签:
10条回答
  • 2020-11-30 10:47

    specify the full path of the file url

    0 讨论(0)
  • 2020-11-30 10:48

    You can't do this without the WEB SERVER!!! Chrome sends XMLHttpRequest to the system that looks something like this

    GET /myFile.txt HTTP/1.1
    

    And the operating system is not listening on port 80 to receive this! And even if it is, it must implement HTTP protocol to communicate with the browser...

    To get this working, you must have WEB SERVER installed on your system, that will listen on port 80 and make your files available through a HTTP connection, thus making your code runnable.

    0 讨论(0)
  • 2020-11-30 10:49

    Something like this is what I use all the time. No need for any base64 decoding.

    <html>
    <head>
    <script>
          window.onload = function(event) {
            document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
          }
    
          function handleFileSelect(event) {
            var fileReader = new FileReader();
            fileReader.onload = function(event) {
              $('#accessKeyField').val(event.target.result);
            }
            var file = event.target.files[0];
            fileReader.readAsText(file);
            document.getElementById('fileInput').value = null;
          }
    </script>
    </head>
    <body>
    <input type="file" id="fileInput" style="height: 20px; width: 100px;">
    </body>
    </html>
    
    0 讨论(0)
  • 2020-11-30 10:55

    A workaround for this I used was to include the data as a js file, that implements a function returning the raw data as a string:

    html:

    <!DOCTYPE html>
    <html>
    
    <head>
      <script src="script.js"></script>
      <script type="text/javascript">
        function loadData() {
          // getData() will return the string of data...
          document.getElementById('data').innerHTML = getData().replace('\n', '<br>');
        }
      </script>
    </head>
    
    <body onload='loadData()'>
      <h1>check out the data!</h1>
      <div id='data'></div>
    </body>
    
    </html>
    

    script.js:

    // function wrapper, just return the string of data (csv etc)
    function getData () {
        return 'look at this line of data\n\
    oh, look at this line'
    }
    

    See it in action here- http://plnkr.co/edit/EllyY7nsEjhLMIZ4clyv?p=preview The downside is you have to do some preprocessing on the file to support multilines (append each line in the string with '\n\').

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