Angular error: Trying to assign a value of type ArrayBuffer to a string type

Is there a way to display a preview of a selected image before uploading it to the server?

Here is an example in HTML:

<div id="drop_zone" (drop)="dropHandler($event)" (dragover)="onDragover($event)">
            <p>drag one or more files to this dropzone</p>
            <img src="" id="imgPreview">
</div>

And here is the corresponding TypeScript code:

dropHandler(ev){

    console.log(ev);
    console.log("file dropped");
    event.preventDefault();
    if (ev.files && ev.files[0]) {
      var reader = new FileReader();

      reader.onload = function (e) {
        var abc=<HTMLImageElement>document.getElementById('imgPreview');
        abc.src=e.target.result;
      };

      reader.readAsDataURL(ev.files[0]);
  }

However, abc.src=e.target.result seems to return an ArrayBuffer. How can I retrieve the URL of the selected image as a string using FileReader?

Answer №1

Your understanding of the fundamentals seems to be spot on. I tried out a simplified version of your code by incorporating a file upload feature, and it appears to be functioning correctly.

https://example.com/edit/angular-abc123

<input type="file" #file (change)="onUpload(file.files[0])" />
<img *ngIf="src" [attr.src]="src" id="imgPreview">
  onUpload(file): void {
    if (!file) {
      return;      
    }

    const reader = new FileReader();
    reader.onload = e => {     
      this.src = <string>e.target.result;
    };
    reader.readAsDataURL(file);
  }

To satisfy the linter, I had to cast e.target.result as a string. However, the JavaScript itself remains unaffected.

Note that while the drop functionality didn't work for me in Stackblitz, the file upload method should operate similarly since both involve handling a File object at their core.

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

"TypeORM's createConnection function on MacOS with PG database returns a Pending status even when using

Running MacOS Catalina version 10.15.4 To replicate the issue, follow these steps using the quick guide: npm install typeorm --save npm install reflect-metadata --save npm install @types/node --save npm install pg --save npm install typeorm -g typeorm in ...

ESLint is parsing through alternative configurations

My .eslintrc file is very simple: { "extends": [ "twilio" ] } However, when I run eslint, I encounter this error message: The config "standard" was referenced from the config file in "/Users/MyAccount/Projects/my-sample-app/node_modules/cipher ...

The JavaScript function is not functioning properly, whereas another function is working as intended

I have created a HTML form with 2 buttons and a table. Each row in the table consists of a checkbox and 2 text fields. The buttons allow users to add and remove rows from the table. The remove button only applies to rows where their checkbox is checked. T ...

Updating the TextField in React Material UI based on the Slider value without affecting the Slider

Is there a way to update the value of a TextField based on the slider, while still allowing manual input in the TextField? I want the TextField to reflect changes from the slider but not vice versa. I attempted making the TextField a controlled component ...

Understanding the attribute types in Typescript React

While working on code using Typescript + React, I encountered an error. Whenever I try to set type/value in the attribute of <a> tag, I receive a compile error. <a value='Hello' type='button'>Search</a> This piece o ...

AngularJS Cascading Dropdowns for Enhanced User Experience

There is a merchant with multiple branches. When I select a merchant, I want another dropdown list to display the data from merchant.branches. The following code does not seem to be fixing the issue: <label>Merchant:</label> <select ng-if= ...

Tips for maximizing efficiency and minimizing the use of switch conditions in JavaScript when multiple function calls are needed

After coming up with this code a few minutes ago, I began to ponder if there was a more elegant way to optimize it and condense it into fewer lines. It would be even better if we could find a solution that eliminates the need for the switch condition altog ...

I'm having trouble managing state properly in Safari because of issues with the useState hook

Encountering Safari compatibility issues when updating a component's state. Though aware of Safari's stricter mode compared to Chrome, the bug persists. The problem arises with the inputs: Whenever an option is selected from the dropdown, it cl ...

Custom-designed background featuring unique styles

I have implemented the following code to create a continuous running banner: <style> #myimage { position: fixed; left: 0%; width: 100%; bottom: 0%; background:url("http://static.giga.de/wp-content/uploads/2014/08/tastatur-bild ...

Tips for creating a secure authentication system in an AngularJS application!

As a novice in the world of angularjs... After going through the documentation and completing a tutorial, I decided to experiment on my own which has helped me grasp things better. Now, I'm looking into creating a secure authentication system. The ...

Any tips for filtering an array within an array of objects using the filter method?

I have an array of products and models that I am currently filtering based on 'id' and 'category'. var app = angular.module("myApp", []); app.controller("myCtrl", function($scope) { $scope.products = [{ 'id': 1, ...

Bing Translator and XMLHttpRequest are two powerful tools for translating and

When running the code snippet below, I encounter an issue where I am not receiving status 200 and responseText. However, when using the following URL: http://api.microsofttranslator.com/V2/Http.svc/GetLanguagesForTranslate?appId=F1B50AB0743B541AA8C070890 ...

Using percentages for sizing and margins in CSS

Looking to create a visually appealing page that always fills the entire screen? Check out this code snippet that does just that: #posts{ width:100%; height:auto; background:#666; } .entry{ float:left; margin-left: 4%; margin-top:10 ...

Updating a URL for all users using React/Next.js and Firebase: a guide to refreshing the page

I am currently developing a Next.js application with a Firebase backend and have encountered an issue. In my setup, users can create sessions that others can join, but only the creator of the session can "start" it, triggering a state change. I need all us ...

What could be causing the state to not update as anticipated?

I am currently in the process of developing a TicTacToe game and have a requirement to maintain the current player in state under the name currentPlayer. The idea is that after one player makes a move, I need to update currentPlayer to represent the opposi ...

To handle the input field efficiently in Angular, consider utilizing two <input type="radio"> elements

I am facing a challenge in my Angular 5 project where I have two radio buttons and need to dynamically update the value of formControlName and placeholder for an input field based on the selected radio button. How can I tackle this issue? <div clas ...

The CKEditor is having trouble properly opening code snippets

I have been using ckeditor 4.4 along with the code snippet plugin. Initially, when I create a document with a rich code snippet and save it, everything works perfectly fine. The source code for what is generated looks like this: <pre><code>&am ...

Is it possible for two overlapping Javascript divs to both be draggable at the same time?

I have multiple stacked div elements. The top one needs to be draggable, while the one beneath should remain clickable. An illustration is provided below for better understanding: The green div elements are contained within cells. Clicking on a cell trigg ...

An example in Typescript for setting an initial/default value for a data type

Can you create a Type with a default value included? For example: type Animal = { kind : "animal" Legs : number, CanFly: boolean } const monkey: Animal = { Legs: 4, CanFly: false}; //In this line, clients must initialize the same value `kin ...

Converted requests from loopback to angular2 resulted in an error message, as the script's MIME type ('text/html') was determined to be non-executable

Currently, I have set up loopback as the backend API and angular2 as the frontend for my project. Loopback is serving my angular2 frontend without any issues. However, whenever I refresh a page, loopback seems to struggle with handling the URL because tha ...