简体   繁体   中英

In an HTML/JavaScript file, how can I select a data file to include?

I have written a graphing program, but each time it runs it should prompt the user for a data file to plot. Here is a very simplified program that has the data file (Data.js) hard coded in line 7:

<!DOCTYPE html>
<html>
  <head>
    <title>Warm-up</title>

    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js"></script/>
    <script src="./Data.js"></script>

    <script>

      function drawHorizontalLine(c, startX, startY, endX, endY) {
        c.lineWidth = 3;
        c.strokeStyle = '#888';

        c.beginPath();
        c.moveTo(startX, startY);
        c.lineTo(endX, endY);
        c.stroke();
      }


      $(document).ready(function() {
        // Set the canvas width according to the length of time of the recording
        var myCanvas = document.getElementById("graph");
        var resultOfCalculation = 100;
        myCanvas.width += resultOfCalculation;

        graphWidened = $('#graph');
        var graphCanvas = graphWidened[0].getContext('2d');

        drawHorizontalLine(graphCanvas, 10, 20, endWidth, endHeight);
      });
    </script/>
  </head>

  <body>
    <canvas id="graph" width="600" height="450">
  </body>
</html>

... where Data.js contains:

var endWidth = 200;
var endHeight = 150;

But I want to select the data file, something like this, perhaps:

<input type="file" id="sourcedFile" />
<p id="chosenFile" ></p>

<script type="text/javascript">
  function readSingleFile(evt) {
    //Retrieve the first (and only!) File from the FileList object
    var f = evt.target.files[0];

    if (f) {
      document.getElementById("chosenFile").innerHTML = f.name;
    } else {
      alert("Failed to load file");
    }
  }

  document.getElementById('sourcedFile').addEventListener('change', readSingleFile, false);
</script>

But I am having difficulty fitting the two pieces together in one file. Obviously it should first request the data file and then draw the graph using the file name stored in the "chosenFile" variable. I am new to HTML and JavaScript.

Thanks.

--- Edit ---

Thanks for your response, @TheGr8_Nik. I incorporated it in this file:

<!DOCTYPE html>
<html>
  <head>
    <title>Warm-up</title>
    <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>

    <input type="file" id="sourcedFile" />
    <p id="makeButtonGoAboveCanvas" ></p>

    <script type="text/javascript">
          var script;
      //
      // This function is called when sourcedFile changes as a result of user selection.
      // It inserts the code lines (actually graph data) contained in sourceFile into this location.
      //
      // Selected files must be in the same directory as this file.  (Why??)
      // When running on a local computer the file selection only works in Firefox browser.
      //
      function insertDataFromSelectedFile(evt) {
        //Retrieve the first (and only!) File from the FileList object
        var f = evt.target.files[0];

        if (!f) {
          alert("Failed to load file");
        }
        else {
          script,
              script_id = 'loaded_script',
              //file_name = "./Data.js";
              //file_name = "http://127.0.0.1:8887/Data.js";
              //file_name = this.value.replace("C:\\fakepath\\", "http://127.0.0.1:8887/");
              //file_name = this.value.replace("C:\\fakepath\\", "");
              file_name = f.name;

          script = document.createElement('script');
          script.id = script_id;    // assign an id so you can delete it after use

          delete(endWidth);                 // To test if sourcing worked
          script.src = file_name;          // set the url to load
          $('head').append( $(script) );    // append the new script in the header

          if (typeof endWidth == 'undefined') {
            alert ("endWidth is undefined. The selected file was not read or did not define endWidth");
          }
          else {
            drawGraph();
          }

          $('#'+ script_id ).remove();  // remove the last loaded script - Seems to be unnecessary
        }
      }

      function drawHorizontalLine(c, startX, startY, endX, endY) {
        c.lineWidth = 3;
        c.strokeStyle = '#888';

        c.beginPath();
        c.moveTo(startX, startY);
        c.lineTo(endX, endY);
        c.stroke();
      }

      function drawGraph() {
        // Draw the graph
        var myCanvas = document.getElementById("graph");
        var resultOfCalculation = 100;
        myCanvas.width += resultOfCalculation;

        graphWidened = $('#graph');
        var graphCanvas = graphWidened[0].getContext('2d');

        drawHorizontalLine(graphCanvas, 10, 20, endWidth, endHeight);
        //drawHorizontalLine(graphCanvas, 10, 20, 400, 80);
      }

      document.getElementById('sourcedFile').addEventListener('change', insertDataFromSelectedFile, false);
    </script>
  </head>

  <body>
    <canvas id="graph" width="600" height="450">
  </body>
</html>

I ran this on a local Windows machine with Chrome browser. Chrome caused huge problems by changing the file path to C:\\fakepath\\ and by complaining about "Cross origin requests are only supported for protocol schemes: http, .....". Changing to Firefox fixed those.

To get the script to work I deleted this line and its closing brace because the onload event didn't seem to be happening: script.onload = function () {

You can use js to inject a script tag in your html:

$( function () {
    $('#sourcedFile').on( 'change', function () {
      var script,
          script_id = 'loaded_script',
          file_name = this.value;

      // check if the name is not empty
      if ( file_name !== '' ) {
        // creates the script element
        script = document.createElement( 'script' );

        // assign an id so you can delete id the next time
        script.id = script_id;

        // set the url to load
        script.src = file_name;

        // when the script is loaded executes your code
        script.onload = function () {
          var myCanvas = document.getElementById("graph");
          var resultOfCalculation = 100;
          myCanvas.width += resultOfCalculation;

          graphWidened = $('#graph');
          var graphCanvas = graphWidened[0].getContext('2d');

          drawHorizontalLine(graphCanvas, 10, 20, endWidth, endHeight);
        };

        // remove the last loaded script
        $('#'+ script_id ).remove();
        // append the new script in the header
        $('head').append( $(script) );
      }
    });
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM