Exploring FileReader and DOMParser for AngularJS applications

I have a user uploaded file using AngularJS and would like to manipulate the file contents using XML. Unfortunately, I am facing an issue with the DOMParser recognizing the text file.

index.html

  <div ng-controller = "myCtrl">
      <input type="file" file-model="myFile"/>
      <button ng-click="uploadFile()">upload me</button>
  </div>

app.js

 myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){

     $scope.uploadFile = function(){
     var file = $scope.myFile;

     reader = new FileReader();
     reader.onload = function() {
     showout.value = this.result;
     txtFile = showout.value;

     console.log(txtFile);
     };

    reader.readAsText(file);
    parser=new DOMParser();

    xmldoc = parser.parseFromString(txtFile,"text/xml"); 
    console.log(xmlDoc);

While the txtFile is printed correctly to the console in the Reader.onLoad section of this example, xmlDoc is showing as undefined.

How should I reference the file and convert it so that it can be read by DOMParser?

NOTE: If I replace txtFile in ... xmldoc = parser.parseFromString("bob","text/xml"), the code works as expected.

Thank you in advance.

Answer №1

Although this information may be dated, I thought I'd provide a functional demonstration for those who may still find it useful.

const parser = new DOMParser();
const reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = function (evt) {
    const data = parser.parseFromString(evt.target.result, "application/xml");
    console.log(data);
};

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

How can I retrieve a data field with a colon in its key using Cytoscape.js?

After diligently going through the official documentation and following the steps in the tutorial, I have successfully managed to access a node's data field and use it for labeling, as long as the key is a simple string. However, my data will contain ...

I experienced an issue with Firestore where updating just one data field in a document caused all the other data to be wiped out and replaced with empty Strings

When updating data in my Firestore document, I find myself inputting each individual piece of data. If I try to edit the tag number, it ends up overwriting the contract number with an empty string, and vice versa. This issue seems to stem from the way th ...

The directive fails to refresh the parent's scope

For all the coding enthusiasts out there, check out the code snippet at this link. Here is a directive example: scope: { attrs: '=?' } Below is the main controller code: this.val = { val: '1', title: '2' }; $scope.$watch( ...

What is the best approach for rendering HTML on a page both initially and dynamically as it is updated, given the heavy utilization of ajax?

One challenge faced by many web applications today is how to efficiently reuse html templates without redundancy when initially rendering a page and adding new content. What is the most effective approach for this? One option is to render the HTML page ...

Even when the outcome is not what was anticipated, mocha chai still manages to ace the examination

When testing my REST API response with mocha, chai, and express, I set the expected status to 201 but unexpectedly got a passing test result it('janus post', () => { request('https://***') .post('/***') .attach(&a ...

What is the best way to insert information from a controller into the navigation bar?

My main controller includes a navbar with the ui-view, as well as a separate controller for handling user login. Once the user logs in, the controller attempts to retrieve the user's information and store it in $scope/$rootScope. Unfortunately, none ...

How to transform a JQuery button into a dropdown menu

For inspiration, consider this JQuery UI Button example: http://jqueryui.com/demos/button/#splitbutton Now, how can you create a dropdown menu when the small button is clicked? My main concern is the way .button() alters the button's actual appearanc ...

Retrieve all the keys from an array of objects that contain values in the form of arrays

Looking for an efficient way to extract all keys from an array of objects whose values are arrays, without any duplicates. I want to achieve this using pure JavaScript, without relying on libraries like lodash or underscore. Any suggestions on how to impro ...

The proxy URL is not functioning properly within the Angular JS controller

Currently, I am in the process of developing an application using expressjs and angularjs. To set up my backend, I utilized the express generator to install essential tools such as mysql, body parser, and cors. For the frontend, I integrated gulp with an ...

ng-token-auth lacks access control functionality

I am currently in the process of developing an Ionic App that utilizes ng-token-auth with a rails API supported by devise-token-auth. Recently, I completed the registration section as per the documentation provided. https://github.com/lynndylanhurley/ng- ...

Utilize key-value pairs to reference variables when importing as a namespace

Is it feasible to utilize a string for performing a lookup on an imported namespace, or am I approaching this the wrong way? Consider a file named my_file.ts with contents similar to: export const MyThing: CustomType = { propertyOne: "name", ...

text/x-handlebars always missing in action

I'm currently working on my first app and I'm facing an issue with displaying handlebars scripts in the browser. Below is the HTML code: <!doctype html> <html> <head> <title>Random Presents</title> ...

Error message: AngularJS Jasmine spyOn: number has no functionality

I am encountering difficulties while attempting to execute a test that utilizes a mockup for a service call (retrieving location data from a web SQL database). Below is the controller code: .controller('LocationDetailCtrl', function ($scope, $s ...

Ways to address the issue of Node.js versions with odd numbers not qualifying for LTS status and being unsuitable for production node:16120 due to UnhandledPromiseRejectionWarning

After attempting to initiate a new Angular application with ng new app, I encountered the following error: Node.js version v11.0.0 detected. Odd numbered Node.js versions will not enter LTS status and should not be used for production. For more information ...

Issue with AJAX communication with C# backend

Currently, I am facing an issue where I am unable to pass information back to the backend code, specifically a user-selected name from a list. I attempted to set the data VN to an object and pass that, but it resulted in errors. It seems that the informati ...

I would like to know the method for inserting an HTML element in between the opening and closing tags of another HTML element using

Recently, I came across a coding challenge involving a textbox. <input type="text></input> The task was to insert a new span element between the input tags using jQuery, as shown below: <input type="text><span>New span element< ...

Is there a way to repeatedly call a function without losing its previous outputs, without relying on a database? What alternative should I consider using instead?

I'm looking to create multiple tables using the same function in JavaScript. However, when I call the function again, the previous table disappears. I am new to coding in JavaScript and would appreciate any suggestions on how to handle this issue. I p ...

Creating a collection by gathering data from interactive fields with the help of AngularJS

I have a project to create an attendance system for employees. The system requires me to track the attendance status of each employee by generating a dynamic form with text input fields and checkboxes using angularjs ng-repeat inside a table. This form wil ...

Storing user input in MongoDB after encoding

I am currently exploring the most effective methods for storing and presenting user input in MongoDB. In traditional SQL databases, it is necessary to encode all user input as a precaution against injection attacks. However, in the context of MongoDB, ther ...

toggle the visibility of an element depending on the function's outcome

When a user logs in to my system, I want the logout button to appear. When logged out, the button should disappear. To implement this, I tried using the following code for a button click: $scope.test = function () { if ($rootScope.authenticated ...