Uploading an image in Typescript on IE11 using Angular 4

I'm having an issue uploading an image to my web application using Angular 4. I convert the input file using readAsBinaryString() and extract the ASCII code using btoa() before passing it to a backend service. While this process works smoothly on Chrome, it encounters problems on Internet Explorer 11.

To address the IE11 compatibility issue, I included the readAsBinaryString() function in the polyfills.ts file:

function str2ab(str) {
  let buf = new ArrayBuffer(str.length);
  let bufView = new Uint8Array(buf);
  for (let i = 0, strLen = str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}

if (!FileReader.prototype.readAsBinaryString) {
  FileReader.prototype.readAsBinaryString = function (fileData) {
    let binary = '';
    let pt = this;
    let reader = new FileReader();
    reader.onload = function (e) {
      let bytes = str2ab(reader.result);
      let length = bytes.byteLength;
      for (let i = 0; i < length; i++) {
        binary += String.fromCharCode(bytes[i]);
      }
      pt.content = binary;
      pt.onload();
    };
    reader.readAsArrayBuffer(fileData);
  };
}

image.component.html

<input type="file" name="image" id="image" accept="image/png, image/jpeg" (change)="fileChange($event)" [(ngModel)]="image" placeholder="Upload image">

image.component.ts

  fileChange = function (evt) {
    let files = evt.target.files;
    let file = files[0];
    if (files && file) {
      let reader = new FileReader();
      reader.onload = (e) => { // 'e' is undefined on ie11!
        let target = <FileReader>e.target;
        let result = target.result as string;
        this.byteArray = btoa(result);
      };
      reader.readAsBinaryString(file);
    }
  };

By adding the polyfills, the readAsBinaryString() function now works on IE11. However, the reader.onload function throws the following error: Unable to get property 'target' of undefined or null reference.

Answer №1

To address the issue discussed here, you can attempt implementing the provided code snippet:

  handleFileChange = function (event) {
    let filesList = event.target.files;
    let selectedFile = filesList[0];
    if (filesList && selectedFile) {
      const reader = new FileReader();

      reader.onload = (event: Event) => {
        // event.target.result; // This is not valid
        console.log(reader.result); // This is correct
     };

      reader.readAsBinaryString(selectedFile);
    }
  };

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

Tips on filtering an array in a JSON response based on certain conditions in Angular 7

Looking to extract a specific array from a JSON response based on mismatched dataIDs and parentDataIDs using TypeScript in Angular 7. { "data":[ { "dataId":"Atlanta", "parentDataId":"America" }, { "dataId":"Newyork", ...

Unable to download files from Angular frontend connected to Spring backend, experiencing corruption or malfunction

I am facing an issue with downloading files (.odt) stored in a mysql database. Here is the code snippet for handling this operation in my project: Backend (using Spring, not Spring Boot): @RequestMapping(value = "/downloadRequest", method = Requ ...

Troubleshooting issue with Express.json() functionality in the latest release of version 4.17

I'm currently exploring the MEAN stack and I am focused on performing CRUD operations. However, when I send data in the request body from Angular to the server, I end up receiving an empty request body. I'm unsure of where I might be making a mis ...

Using MatTableDataSource in a different Angular component

I am working with two components, namely Order and OrderDetail. Within the Order component, I have a MatTableDataSource that gets populated from a service. OrderComponent Prior to the constructor listData: MatTableDataSource<DocumentDetailModel>; ...

Utilizing Angular's NgFor directive to showcase the elements within the array

Just diving into Angular and attempting to access the values within postdata. However, I'm running into an issue where only the first value is being retrieved when I try to iterate over it. Here's a snippet of my code: posts; constructor(priva ...

Exploring the Functionality of Algolia Places within a Next.js Application

Currently, I am working on integrating the Algolia Places functionality into my next.js project using TypeScript. To begin, I executed npm install places.js --save Next, I inserted <input type="search" id="address-input" placeholder ...

Is there a method in Typescript to constrain an exported function's accessibility so that it is only importable by specific files?

I would like developers to use a class or interface instead of directly importing functions. Is there a way to restrict so only the class can import the function? I prefer not to consolidate all the functions in a single file, especially in a large proje ...

What is causing this CORS error in my Angular request?

I currently have a Controller implemented in Angular 4 that makes a request to the NBA API Stats. When I test this request in Postman, I can see all the data without any issues. However, when I execute the same request in my Angular application, I encounte ...

Angular2 Final: Issue with inline template - incorrect format for number pipes

Problem <h2>{{totalTargetValue | currency:'EUR':true:'2'}}</h2> Issue Error while using inline template: the specified digit info for number pipes is invalid. Do you have any suggestions on how to resolve this error? ...

Encountering issues with Angular 12 optimized build, the error messages are sparse and offer little

While my project compiles without any issues in development mode with the build optimizer turned off, I encounter an error during production build: ✔ Browser application bundle generation complete. ✔ ES5 bundle generation complete. ✔ Copying assets c ...

Angular's array filter functionality allows you to narrow down an

I am working with an Array and aiming to filter it based on multiple criteria: primasSalud = [ { nombre: 'one', internacional: true, nacional: false, nacionalSinReembolso: false, nacionalClinicasAcotadas: false ...

The TypeScript, NextJS project is encountering an issue where it is unable to read the property 'cwd' due to a TypeError

I've noticed this particular error popping up frequently online, but it's not quite matching the issue I'm facing. Every time I execute yarn dev, I encounter the following error: next-dev.js?53bc:89 Error was not caught TypeError: Cannot re ...

Issue encountered with JavaScript function within TypeScript file connected to HTML code

I am currently working on a simple SharePoint web part and encountering an issue with using a function from another module file in my main file. Snippet from the JSFunctions.module.js file (where I define my function): function getApi(){ [my code]... }; ...

What is preventing form validation from functioning properly with both built-in and cross-field validators?

I've been facing issues while trying to develop a form with built-in validators and cross-field validator. Unfortunately, the functionality is not working as expected and I'm struggling to understand why. The form should contain four types of bu ...

When we mention TypeScript and CDK, we are actually talking about the very foundation

As I was working on my current Stack constructor, I came across the Stack.formatArn() method. I started to wonder about the difference between using this.formatArn() and cdk.Stack.of(this).formatArn(). After all, shouldn't "this" refer to the stack it ...

Guide: Implementing service utilization within a controller using Express and Typescript

This specific piece of TypeScript code is causing me some trouble. I'm attempting to utilize a service to retrieve data from a database, but unfortunately, I keep encountering the following error message: Cannot read property 'populationService&a ...

Is it possible to link all form inputs to URL query parameters using AngularDart?

I am currently working on an AngularDart application and I have a requirement where I need to bind form input to the URL, which represents settings. The purpose of this is to allow users to share a link with others so that they can view what has been input ...

Verify if the keys are present within the object and also confirm if they contain a value

How can we verify keys and compare them to the data object? If one or more keys from the keys array do not exist in the object data, or if a key exists but its value is empty, null, or undefined, then return false; otherwise, return true. For example, if ...

Is it possible to utilize terms such as 'calc' within the [style.width] directive?

Can I incorporate my variable into calc() within the [style.width] directive in angular? For example: <div [style.width.px]="calc(100% - myWidth)">some texts </div> ...

Creating a TypeScript rule/config to trigger an error when a React Functional Component does not return JSX

I've encountered a recurring issue where I forget to include a return statement when rendering JSX in a functional component. Here's an example of the mistake: const Greetings = function Greetings({name}) { <div>Greetings {name}</div& ...