0

So I have an assignment to connect a CSV in an S3 bucket to a static webpage using JavaScript. I know it's easy enough to use JavaScript to upload and display a csv that the user enters, but instead I want the user to press a button and have the whole CSV loaded/displayed on the webpage. I have a button now called "Generate Statistics" that I'm hoping will do three things: upload csv, display csv, and display some static text such as average age. I'm partially doing this as a workaround to using Lambda, because I've failed miserably with that so far.

Ideally, I want the page to initially look like this: enter image description here

Then, after the user clicks the button, I would like the page to upload the dataset like below. Note that I was only able to accomplish this by having the user manually upload the csv from local, which is why the file upload button is still there. I hope to get rid of this button and have only the "Generate Statistics" button work.:enter image description here

I'm getting a 404 Error when I run this in a fiddle. Does anyone know where I may be going wrong?

My html code is below. I got the csv formatting part from this GitHub and the JavaScript/S3 connection part from here.

<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title>HTML5 File API</title>
</head>
<body >
  <div>
    <form class="form-horizontal well">
      <legend>
        <h3>
          <div id="title">HTML5 File API</div>
        </h3>
      </legend>
      <fieldset>
          <label for="csvFileInput"> <strong>CSV File:</strong>
          </label>
          <button onclick="myFunction()">Generate Statistics</button>
        </div>
      </fieldset>
    </form>
    <div id="output">
    <p id="demo"></p>
    </div>
  </div>
  <br>
  <br>
  <footer>
    <center>
      <p>&copy; Mounir Messelmeni 2012</p>
    </center>
  </footer>

  <!-- Le javascript
    ================================================== -->
  <!-- Placed at the end of the document so the pages load faster -->
  <script type="text/javascript" src="js/read-csv.js"></script>

  <script>
  function myFunction() {
    myvar = 'Average Age is 37';
  document.getElementById("demo").innerHTML = myvar;}
  </script>

  <script src="messages.js">
  var AWS = require('aws-sdk');
  AWS.config.update(
    {
      accessKeyId: "X",
      secretAccessKey: "X",
    }
  )
  var s3 = new AWS.S3();
  s3.getObject(
    { Bucket: "fakeemployee", Key: "Employee_Attrition_Data.csv" },
    function (error, data) {
      if (error != null) {
        alert("Failed to retrieve an object: " + error);
      } else {
        alert("Loaded " + data.ContentLength + " bytes");
        // do something with data.Body
        var csv = data.Body;
        processData(csv);
      }
    }
  )
  function processData(csv) {
      var allTextLines = csv.split(/\r\n|\n/);
      var lines = [];
      while (allTextLines.length) {
          lines.push(allTextLines.shift().split(','));
      }
    console.log(lines);
    drawOutput(lines);
  }

  //if your csv file contains the column names as the first line
  function processDataAsObj(csv){
      var allTextLines = csv.split(/\r\n|\n/);
      var lines = [];

      //first line of csv
      var keys = allTextLines.shift().split(',');

      while (allTextLines.length) {
          var arr = allTextLines.shift().split(',');
          var obj = {};
          for(var i = 0; i < keys.length; i++){
              obj[keys[i]] = arr[i];
    }
          lines.push(obj);
      }
          console.log(lines);
    drawOutputAsObj(lines);
  }

  function errorHandler(evt) {
    if(evt.target.error.name == "NotReadableError") {
        alert("Canno't read file !");
    }
  }

  function drawOutput(lines){
    //Clear previous data
    document.getElementById("output").innerHTML = "";
    var table = document.createElement("table");
    for (var i = 0; i < lines.length; i++) {
        var row = table.insertRow(-1);
        for (var j = 0; j < lines[i].length; j++) {
            var firstNameCell = row.insertCell(-1);
            firstNameCell.appendChild(document.createTextNode(lines[i][j]));
        }
    }
    document.getElementById("output").appendChild(table);
  }

  //draw the table, if first line contains heading
  function drawOutputAsObj(lines){
    //Clear previous data
    document.getElementById("output").innerHTML = "";
    var table = document.createElement("table");

    //for the table headings
    var tableHeader = table.insertRow(-1);
    Object.keys(lines[0]).forEach(function(key){
        var el = document.createElement("TH");
        el.innerHTML = key;
        tableHeader.appendChild(el);
    });

    //the data
    for (var i = 0; i < lines.length; i++) {
        var row = table.insertRow(-1);
        Object.keys(lines[0]).forEach(function(key){
            var data = row.insertCell(-1);
            data.appendChild(document.createTextNode(lines[i][key]));
        });
    }
    document.getElementById("output").appendChild(table);
  }
  </script>
  </body>
  </html>

EDIT: I have confirmed that the s3 bucket/key is correct. Please see screenshot of my bucket: enter image description here

Kelsey
  • 401
  • 9
  • 21
  • Using your `accessKeyId` and secret key like that is not a good practice. Hope that you know that? Also I would diactivate them asap. – Marcin Jul 09 '21 at 05:38
  • You should _never_ show your Secret Key to anyone. Please immediately disable those credentials or somebody could have access to your account. There is _never_ a need to put those credentials in your code. Instead, use a credentials configuration file. See: [Setting Credentials in Node.js - AWS SDK for JavaScript](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials-node.html) – John Rotenstein Jul 09 '21 at 05:55
  • @JohnRotenstein and Marcin thank you both for letting me know! I literally hadn't realized that. – Kelsey Jul 09 '21 at 13:15
  • 404 suggests that you have permissions (otherwise it would be 403) but the requested object does not exist. Check the bucket/key combination using the awscli or other. – jarmod Jul 09 '21 at 13:30
  • @jarmod I've confirmed that the bucket/key combination is correct. I've updated my question with a screenshot of the bucket as well in case I'm missing something. – Kelsey Jul 09 '21 at 13:46

0 Answers0