What is the best way to showcase the content from multiple uploaded files?

Below is an example demonstrating how to display the contents of a single uploaded file.

.js

$scope.uploadFilename = function (files) {
          if (!files[0]) {
            return;
          }

          var reader = new FileReader();

          reader.onload = function (e) {
            var str = reader.result;
            var csv = str.split(/\n/);
            var headers = csv[0].split(',');
            var str_result = '';
            for (var i = 1; i < csv.length - 1; i++) {
              var curline = csv[i].split(',');
              var tmp = '' + curline[1];
              if (i == csv.length - 2) {
                str_result += tmp.split('"').join('');
              } else {
                str_result += tmp.split('"').join('') + '\n';
              }
            }
            angular.element('#upload_keywords_list').val(str_result);
            $scope.uploadedKeywordsCount = csv.length - 2;
          };
          reader.readAsText(files[0]);
        };

.html

<div class="chosefile">
              <div class="clearfix">
                <input type="file" name="file" class="pull-left" onchange="angular.element(this).scope().uploadFilename(this.files)">
<textarea id="upload_keywords_list" class="form-control" rows="10"></textarea>
              <div class="uploaded-keywords-count" ng-if="uploadedKeywordsCount > 0">
                <strong>Total number: </strong>{{ uploadedKeywordsCount }}
              </div>
            </div>
          </div>

I am looking to display the contents of multiple uploaded files. Could someone guide me on how to achieve this? Also, what is the process to update the total number value when modifying the textarea content that has been previously opened?

Thank you.

Answer №1

Hopefully, this solution is effective.

I have made modifications to your HTML by removing uploaded-keywords-count and textarea, and introducing a new div.

<div id="textAreaContainer"></div>

In addition, I have updated your script by enclosing the code within a for loop. This enhancement allows you to select multiple files either simultaneously or individually without any issues.

If you attempt to choose the same file again, a warning will be displayed, and the file selection will be rejected.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  <div ng-app="fileApp" ng-controller="myCtrl">

    <script>
      var app = angular.module('fileApp', []);
      app.controller('myCtrl', function($scope) {
        var allFiles = [];
        $scope.uploadFilename = function (files) {
          if (!files[0]) {
            return;
          }

          cnt = files.length;
          for (var k = 0; k < cnt; k++) {
            if(!allFiles.includes(files[k].name)) {
              var reader = new FileReader();
              reader.fileName = files[k].name;
              allFiles.push(reader.fileName);
          reader.onload = function (e) {
            var str = e.target.result;
            var csv = str.split(/\n/);
            var headers = csv[0].split(',');
            var str_result = '';
            for (var i = 1; i < csv.length - 1; i++) {
              var curline = csv[i].split(',');
              var tmp = '' + curline[1];
              if (i == csv.length - 2) {
                str_result += tmp.split('"').join('');
              } else {
                str_result += tmp.split('"').join('') + '\n';
              }
            }
            $scope.uploadedKeywordsCount = csv.length - 2;
            var containerData = "";
            containerData += '<div id="fileContent' + k + '"><textarea>' + str_result + '</textarea>';
            containerData += '<span>' + $scope.uploadedKeywordsCount + '</span></div>'
            var containerHtml = $(containerData);
            angular.element('#textAreaContainer').append(containerHtml);
          };
          reader.readAsText(files[k]);
          //console.log(files[k]);
        } else {
          alert('File already exists');
        }

      }
    }
  });
      $(document).on('keyup', 'textarea', function(){
        $(this).closest("div").find('span').html($(this).val().split(/\n/).length);
      })
    </script>


    <div class="chosefile">
      <div class="clearfix">
        <input type="file" name="file" class="pull-left" onchange="angular.element(this).scope().uploadFilename(this.files)" multiple>
        <div id="textAreaContainer"></div>
      </div>
    </div>

  </div>

Additionally, I have included a new script to address your second query. Now, whenever you make edits in the textarea, the line count automatically adjusts.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript animation for sequencing traffic lights

I have been working on completing a task that was assigned to me. (iii) Explain the organization of an array that could manage the traffic light sequence. (iv) Develop a script that utilizes the array outlined in part (iii) to create an animated display ...

Associate an alternate attribute that is not displayed in the HTML component

Imagine there is a collection of objects like - var options = [{ id: "1", name: "option1" }, { id: "2", name: "option2" } ]; The following code snippet is used to search through the list of options and assign the selected option to anot ...

Struggling to integrate the c3 chart library with Angular, encountering loading issues

I've been attempting to utilize the c3 angular charts, but unfortunately nothing is displaying on my page. Despite checking for console errors and following a tutorial, I still can't seem to get anything to show up. I have cloned the git repo an ...

What is the recommended way to emphasize an input field that contains validation errors using Trinidad (JSF)?

Trinidad currently displays error messages and highlights labels of failed inputs after client-side form validation. However, I need to directly highlight the input fields themselves. Is there a way to achieve this without resorting to a hack like attach ...

"Exploring the Power of ZF2 with Restful APIs and Image

I am currently in the process of developing a website utilizing Zend Framework 2 in combination with AngularJS. The backend consists of a restful webservice running on ZF2, while AngularJS is used on the client side to interact with this webservice. My ne ...

Displaying a progress bar while fetching data in Vue: A step-by-step guide

I am working on developing a progress bar using vue js and bootstrap for my desktop application. Within the template, I have the code that will generate the necessary markup: <div class="container-fluid p-0 vh-100" v-if="isLoading&quo ...

sum inside the while loop

Below is the provided HTML: <form> <textarea id="input1"></textarea> <textarea id="input2"></textarea> <span></span> </form> The following JavaScript code is included: $("#input2").keyup{ var a = ...

A guide to accessing the currently hovered element on a Line Chart with Recharts

Just diving into this community and also new to ReactJS :( https://i.stack.imgur.com/k682Z.png I'm looking to create a tooltip that displays data only when hovering over the value 1 line. Unfortunately, the current tooltip is not behaving as expecte ...

Enhancing Your WordPress Menu with Customized Spans

I have a WordPress menu structured like this: <div id="my_custom_class"> <ul class="my_custom_class"> <li class="page_item"><a href="#">page_item</a> <ul class='children'> <li class="page_item chil ...

Utilize the toString function along with the substring method within an ejs template

I am attempting to showcase an employee's ID by displaying only the last four digits in a table on an EJS page. The data is stored in MongoDB and I am using Express for handling routes. Here is my Express route: app.get('/routehere', async ...

Choose an option from a list of items in a nested array by

I'm working with a nested array (3d) and I want to populate a drop-down select menu with its values using PHP and jQuery I've tried implementing this for two-level arrays like categories and sub-categories, but what if some sub-categories have f ...

Automatically rehydrate an instance using Angular and JavaScript

REVISION Special thanks to Shaun Scovill for providing an elegant solution using lodash // Creating an instance and injecting server object - within the ChartService implementation below var chart = new Chart(serverChartObject); // Replacing ...

Navigating with router.push in Vue.js to the same path but with different query parameters

The existing URL is /?type=1 I am attempting to implement router.push on this specific page. this.$router.push('/?type=2'); However, it results in a NavigationDuplicated error. I prefer not to utilize parameters such as /:type ...

Encountering build errors in .xproj file when working with Type Script in ASP.Net Core

I recently started working on a new ASP.Net Core project and decided to integrate Angular 2 and Type Script by following a blog post tutorial. However, upon adding a Type Script file to my project, I encountered several build errors from the xproj file. R ...

Tips for avoiding infinite re-render loop when updating state in React/Next.js

I currently have a unique Next.js application that showcases randomly selected YouTube videos. The state within the app is structured as follows (managed by Redux): const state = { entities: { videos: { 'vidId1': { ...

How can you hide all siblings following a button-wrapper and then bring them back into view by clicking on that same button?

On my webpage, I have implemented two buttons - "read more" and "read less", using a Page Builder in WordPress. The goal is to hide all elements on the page after the "Read More" button upon loading. When the button is clicked, the "Read More" button shoul ...

How to retrieve an anchor element from a list using JavaScript

My current code loops through each <li> within a <td> cell and adds a class to the <li>. I have now inserted <a> tags between each <li> and am facing challenges in accessing the <a> tags. What I actually want is to assig ...

Manipulating rows [using an input field] within a table

As someone new to JavaScript, I tried my hand at coding the following piece after tweaking a tutorial I stumbled upon. The aim was to have rows with input fields added and removed within a table, but unfortunately, nothing happens when running the code. ...

Challenges faced with dividing a string in JavaScript

Having trouble splitting a string in JavaScript, I can't seem to make it work. This is the JavaScript code I am using: var str = 'TestApplication20 Application200'; var parts = str.match(/(\d+)(\D.+)/).slice(1); var id = parts[0 ...

What is the code in CodeIgniter to retrieve the string 'Sugar & Jaggery, Salt' using <a>?

Can someone please help me? I am a beginner in CodeIgniter and I am having trouble passing a URL with a string. The controller is not accepting the string as expected. How can I fix this issue? //Below is the HTML code for passing a string value index.ph ...