Error occurred while attempting to use 'readAsText' on 'FileReader': the first parameter is not a valid 'Blob' type

Struggling to access and read a user-supplied XML file within an Angular environment. Here is my current code:

Component.ts:

convertFileToString(event){
    this.uploadXML=event.target.files[0];
    let fileReader = new FileReader();
    fileReader.onload = (event) =>{this.finalUploadedXML=fileReader.result as String}
    fileReader.readAsText(this.uploadXML);
    console.log("The contents are:")
    console.log(this.finalUploadedXML);
  }

index.html

<input type="file" id="uploadInput" (change)="convertFileToString($event)" hidden>

However, upon running the above code, I encounter the following error message:

Failed to execute 'readAsText' on 'FileReader': parameter 1 is not of type 'Blob'

I attempted to adjust readAsText(this.uploadXML) to

readAsText(this.uploadXML.asInstanceOf[Blob])
, but it appears that asInstanceOf is not recognized as a valid property for the File type. Next, I tried changing the data type of uploadXML from File to Blob, yet the error persists. Any suggestions?

Answer №1

Today, I encountered an upload problem and stumbled upon this helpful link. The example provided here addresses the specific issue that I faced, which led me to modify the Angular code for my own project. Hopefully, you may also find it useful.

HTML Code

<form>

  <input type="hidden"
         id="MAX_FILE_SIZE"
         name="MAX_FILE_SIZE"
         value="300000" />

  <div>
    <label for="fileselect">Files to upload:</label>
    <input type="file"
           id="file-select"
           name="fileselect[]"
           multiple="multiple" />

    <div id="file-drag">{{ dragDropAreaText }}</div>
  </div>

</form>

Style Code

#file-drag {
  font-weight: bold;
  text-align: center;
  padding: 1em 0;
  margin: 1em 0;
  color: #555;
  border: 2px dashed #555;
  border-radius: 7px;
  cursor: default;
}

#file-drag.hover {
  color: #f00;
  border-color: #f00;
  border-style: solid;
  box-shadow: inset 0 3px 4px #888;
}

img {
  max-width: 100%;
}

pre {
  width: 95%;
  height: 8em;
  font-family: monospace;
  font-size: 0.9em;
  padding: 1px 2px;
  margin: 0 0 1em auto;
  border: 1px inset #666;
  background-color: #eee;
  overflow: auto;
}

Typescript Code

export class UploadMediaComponent implements OnInit, AfterViewInit {

  constructor(
    private elementRef: ElementRef
  ) { }

  fileList: any[] = [];

  @Input() dragDropAreaText: string = 'Drag and drop files here';
  @Input() uploadButtonText: string = 'Browse File';

  @Output() mediaUploaded: EventEmitter<any> = new EventEmitter();

  ngOnInit() {
  }

  ngAfterViewInit() {
    if (window.File && window.FileList && window.FileReader) {
      setTimeout(() => {
        this.setEvents();
      }, 2000);
    }
  }

  setEvents() {
    const fileDragElement = this.elementRef.nativeElement.querySelector('#file-drag');
    const fileSelectElement = this.elementRef.nativeElement.querySelector('#file-select');
    fileSelectElement.addEventListener('change', this.fileSelectHandler.bind(this));
    fileDragElement.addEventListener('dragover', this.fileDragHover.bind(this));
    fileDragElement.addEventListener('dragleave', this.fileDragHover.bind(this));
    fileDragElement.addEventListener('drop', this.fileSelectHandler.bind(this));
  }

  fileDragHover(e) {
    e.stopPropagation();
    e.preventDefault();
    e.target.className = (e.type == "dragover" ? "hover" : "");
  }

  fileSelectHandler(e) {
    e.preventDefault();
    // cancel event and hover styling
    this.fileDragHover(e);
    // fetch FileList object
    var files = e.target.files || e.dataTransfer.files;
    console.log(files)
    // process all file objects
    for (var i = 0, file; file = files[i]; i++) {
      this.parseFile(file);
    }
  }

  parseFile(file) {
    console.log(file);
    // display an image
    if (file.type.indexOf("image") == 0) {
      var reader = new FileReader();
      reader.onload = (e) => {

        console.log(e);
        console.log(e.target.result);

        file.src = e.target.result;
        this.fileList.push(file);
        this.mediaUploaded.emit(this.fileList);
      }
      reader.readAsDataURL(file);
    }

    // display text
    if (file.type.indexOf("text") == 0) {
      var reader = new FileReader();
      reader.onload = function (e) {
        console.log(e);
      }
      reader.readAsText(file);
    }

  }

}

Answer №2

When calling the convertFileToString() function, it is recommended to pass the file object instead of the event as a parameter. This adjustment is necessary because the function is ultimately invoked by another function that deals with the change event triggered during file upload. Therefore, the revised code looks like this:

convertFileToString(file){
    //this.uploadXML=event.target.files[0];

    let fileReader = new FileReader();
    fileReader.onload = (event) =>{

      this.finalUploadedXML=fileReader.result as String
      console.log((<FileReader>event.target).result);
    }
    fileReader.readAsText(file);
    console.log("The contents are:")
    console.log(this.finalUploadedXML);
}

I hope this clarification proves helpful. Thank you!

Answer №3

Consider using a structure similar to the following when working with your "fileReader.readAsText(this.uploadXML)" method:

if (typeof this.uploadXML === "object") {
  fileReader.readAsText(this.uploadXML);
}

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

Is it true that Angular 4 routers only maintain a single state during navigation?

After transitioning from state A to state B in my application, I noticed that when navigating back to state A, it seems to reload. Does this mean that State A is being destroyed during the transition to state B? If so, how can I prevent State A from relo ...

Creating a Map from an array of key-value pairs: A step-by-step guide

Arrays are essential in programming const myArray = [['key1', 'value1'], ['key2', 'value2']]; Creating a Map from an array is a common task. However, sometimes things don't go as planned: const myMap = new M ...

Compiling angular and ngrx: errors when tap() is removed

I have a snippet of code (slightly simplified) that is functioning correctly and the console logs are displaying everything properly, with valid parameters passed: return observable.pipe(map(response => ({ response, param2, param3, param4, param5 }))) ...

What are the best strategies for managing npm dependencies alongside other packages?

I am working on an Angular app that has the following dependencies: "dependencies": { "personalUiLibrary": "1.0.0" }, "devDependencies": { "tailwindcss": "^2.2.7" } In the personalUiLibrary p ...

The find functionality in Angular and Firebase seems to be malfunctioning

enter image description here Whenever I try to find the ID and data set is not set on these fields, I encounter an error in my console. The following code snippet displays the find expense code: import { Component } from '@angular/core'; import ...

Angular is encountering a situation where code is being executed before properly waiting for the response from an asynchronous

I am in need of a solution that will ensure my function waits for a response before proceeding. I want to prevent the response from being empty and ensure that my code waits for the completion of the asynchronous call. asyncReq(element: any) { this.confl ...

Tips for accessing the data type of a nested property in TypeScript

If I want to keep the following declarations as they are, how can I specifically retrieve the type of the members property? export type Members = { __typename?: 'Members'; id?: Maybe<Scalars['String']>; ... }; export type P ...

What is the method for incorporating an Angular variable into an iframe src link?

Hello there, I appreciate your assistance. I am currently in the process of developing an Ionic app using Angular. One of the tabs within the app is required to dynamically load a specific webpage based on a particular date. I have opted to use an iframe ...

Ionic Framework: Implementing a search bar in the navigation bar

I am looking to include a search icon in the navbar of my Ionic project <ion-navbar> <ion-buttons left> <button ion-button menuToggle> <ion-icon name="menu"></icon-icon> </button> </ion-bu ...

Error: Unable to locate package "@angular-devkit/build-angular" during ng serve command

I have encountered an issue for which I have found a supposed solution here. Unfortunately, none of the provided answers have resolved the problem for me. The error message I am getting is as follows: Could not find module "@angular-devkit/build-angular" ...

What is the best way to include an image in a form and transmit it as payload to the backend using Angular/TypeScript?

What is the process for attaching an image to a form in order to send it as a payload to the backend for saving in a database using Angular/TypeScript? ...

What is the reason for the successful compilation of "require" and the failure of "import"?

Currently getting familiar with TypeScript/JavaScript, as well as Node.js, I am in the process of creating a basic script to run via command line. After adding the dependency archiver and inserting import archiver from 'archiver';to my script, I ...

The Angular file management API from ng6-file-man seems to be malfunctioning

I have downloaded the API, but I am having trouble grasping the concept of parentpath. I attempted to use Postman to call the API at https://github.com/Chiff/ng6-file-man-express, but without success. There seems to be a "files" folder at the root - is t ...

I'm facing an issue in Angular 4 where the routing for a child component is

I'm currently working on implementing routing in my Angular app for movies. I've set up a movie component and an edit movie component. The edit movie component is nested within the movie component, as shown in the folder structure below: https: ...

The component is failing to store its value within the database

I'm encountering an problem when attempting to save an option in the database. To address this issue, I created a component in Svelte called StatePicker that is responsible for saving US States. However, when I try to save it in the database using a ...

I am unable to loop through the object Object

Looking at my JSON data structure, here's what it looks like: {"id":1,"category":"cat","iconUrl":"www.test.com","subCategoryEntity":[{"id":3,"subCategory":"sub3" ...

Angular 2: Export Data to CSV and Download

My backend is built in a Spring Boot application where I am returning a .csv file. @RequestMapping(value = "/downloadCSV") public void downloadCSV(HttpServletResponse response) throws IOException { String csvFileName = "books.csv"; ...

What could be the reason behind the material table not populating with data from the source, despite the service returning an array?

Currently, I am utilizing a mean stack in order to craft a bug tracking system. The issue arises when my express.js service returns an array of issues, which I assign to another array that functions as the dataSource for mat-table. However, despite the ar ...

Encountered a specific issue with Angular 8's mat-autocomplete: "matAutocomplete" is not being recognized as a valid property of the "input" element

Currently, I am attempting to implement the example here from materialUI while working with Angular 8. The mat-chip-list functions properly without the mat-autocomplete feature, but I require it for my project. Below is a snippet of my code: <mat-chip ...

The error message states that the object literal can only define properties that are known, and in this case, 'tailwindcss' is not recognized in the type 'NuxtConfig'

I'm facing an issue in my nuxt.config.ts file while trying to set up a custom tailwind css path. The error I keep encountering can be viewed here. Can someone guide me on how to properly create the custom tailwind css path in my nuxt.config.ts file? ...