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

Personalized HTML selection list

When a select option is too long, it stretches the container to accommodate its length. I have created a truncate function to limit the display to 20 characters and add ellipses to prevent this stretching. I have been searching for a way to show the entir ...

Iterate through the loop to add data to the table

Looking for a way to append table data stored in local storage, I attempted to use a loop to add cells while changing the numbers based on row counts. Here is my JavaScript code snippet: $(function() { $("#loadTask").change(function() { var ta ...

Choosing multiple values in the selectize plugin from the controller: A step-by-step guide

Need help with selecting multiple options I'm utilizing the following plugin: https://github.com/selectize/selectize.js/blob/master/docs/usage.md I have an object as displayed in the image below: https://i.stack.imgur.com/sQsKe.png This is my Client ...

Using backslashes to escape JSON values within a value in Angular

When retrieving JSON data from the backend, I often encounter an issue where the value is set to "key": "\$hello" and it results in an "Unexpected token d". Is there a way in Angular to handle or escape these characters once received from the server? ...

NestJS: Specify the data type for @Body()

Consider the code snippet below: @Post() public async createPet(@Body() petDetails: PostPetDto): Promise<any> { } In this scenario, the type of @Bod() petDetails defaults to plain/any instead of the declared type of PostPetDto. What is the recommen ...

Tips for isolating data on the current page:

Currently, I am using the igx-grid component. When retrieving all data in one call and filtering while on the 3rd page, it seems to search through the entire dataset and then automatically goes back to "Page 1". Is there a way to filter data only within th ...

My browser isn't triggering the jQuery change event, although it does work in jsfiddle

Whenever a textbox is changed, I want a specific function to be executed automatically. The code snippet below demonstrates my approach: var div = document.getElementById("tree"); var input = document.createElement('input'); input.id = 123; i ...

What is the best way to adjust the specific scope of every element generated by ng-repeat within a directive?

Attempting to simplify tables in Angular, I am working on a directive. My goal is for the user to only need to provide the list object and the formatting of each list element in the HTML, using the my-table tag as shown below... <h3>My Table</h3& ...

Guide on adjusting PHP variable values and updating functions with ajax requests

One of my functions determines dates based on a variable For example: $modification = "+1 Week" function updateCalendar($change){ $month = array("January","February","March","April","May","June","July","August","September","October","November","Dece ...

An alternative method for storing data in HTML that is more effective than using hidden fields

I'm trying to figure out if there's a more efficient method for storing data within HTML content. Currently, I have some values stored in my HTML file using hidden fields that are generated by code behind. HTML: <input type="hidden" id="hid1 ...

Incremental migration to Next.js within the current React application

I'm on a quest to uncover practical examples demonstrating the process of gradually transitioning an existing React application towards Next.js. Despite delving into all available Next.js documentation on incremental adoption strategies like subpaths, ...

What confusion do I have regarding resolving promises in Angular's state management?

Here is the state defined in appRouteConfig.js, where I am using $promise to verify userList: .state('userAccounts',{ url:'/userAccounts', controller:'UserAccount', resolve:{ registerService: "registerServ ...

Error in the Angular-UI calendar

I'm encountering an issue while trying to set up the angular-ui calendar. When I run it, I get the following error: TypeError: undefined is not a function at Object.eventsWatcher.onChanged (http://localhost/fisioGest/js/calendar.js:262:41) Despite b ...

Press the [Submit] button to conceal DIV Container 1, reveal DIV Container 2, and populate DIVs discovered in a .PHP file within DIV Container 2

Trying to achieve the following steps: 1 - Press Submit Button 2 - Conceal DIV Container 1 3 - Reveal DIV Container 2 4 - Load and display all DIVs from "PricingDisclaimer.php" into Div Container 2 DIV Code snippet: <div id="MainContainer"> &l ...

Modify the text inside a div based on the navigation of another div

Hey there, experts! I must confess that I am an absolute beginner when it comes to JavaScript, JQuery, AJAX, and all the technical jargon. Despite my best efforts, I'm struggling to grasp the information I've found so far. What I really need is ...

Incorporating jquery-ui Datepicker with dynamic text input functionality

In my table list, I have multiple input fields with the jQuery datepicker implemented. Each input field is assigned the class "datepicker" and a unique ID number. When clicked on, the datepicker pops up allowing for date selection to be inserted into the f ...

Guide on retrieving POST data in sveltekit

Hello, I'm new to sveltekit and I am trying to fetch post data in sveltekit using a POST request. Currently, I am utilizing axios to send the post data. const request = await axios .post("/api/user", { username, email, ...

Express.js experienced a 404 error when processing POST requests

When working with js and express, the route handler file looks like this: var express = require('express'); var passport = require('passport'); var authRoutes = App.route('authRoutes'); va ...

Implementing the Applet Param Tag using JavaScript or jQuery

<applet id="applet" code="myclass.class"> <param name="Access_ID" value="newaccessid"> <param name="App_ID" value="newappid"> <param name="Current_Url" value="newticketurl"> <param name="Bug_ID" value="newbugid"&g ...

Can you explain the distinction between the GenerateSW and InjectManifest choices within the vue ui pwd configuration?

Currently utilizing @vue/cli for building a vue project. I have initiated vue ui to access the vue UI and am in the process of customizing various available options. https://i.sstatic.net/h77AE.png Within Configuration -> PWA, I have come across the a ...