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

Guide: Passing and reading command line arguments in React JavaScript using npm

When launching the react application, I utilize npm start which is defined in package.json as "start": "react-scripts start -o". Within the JavaScript code, I currently have: const backendUrl = 'hardCodedUrl'; My intention ...

Methods for presenting text from an object array using Angular

I'm running into a bit of trouble with getting my text to show up properly in my code. In the HTML, I have <td>{{cabinetDetails.cabinetType}}</td> and my data source is set as $scope.cabinetDetails = [{cabinetType: 'panel'}]; De ...

Expand and enhance your content with the Vue Sidebar Menu plugin

Recently, I integrated a side-bar-menu utilizing . My goal is to have a sidebar menu that pushes its content when it expands. Any suggestions on which props or styles I should incorporate to achieve this effect? Below is my Vue code: <template> ...

I am struggling to grasp the issues with the RxJS v6 migration

After upgrading to Angular 6, I neglected to install rxjs-compat. This resulted in changes needed in my code. import {Observable} from "rxjs/Observable"; was changed to import {Observable} from "rxjs"; and so forth. However, when running ng serve, I ...

Struggling to eliminate buttons upon clicking, but they persistently reappear (JavaScript, HTML)

I have encountered an issue with buttons in my table that I am struggling to resolve. Each row in the table contains a "Pack" action button, which when clicked, is removed to prevent accidental double-packing of items. Everything was functioning smoothly ...

Population of the global namespace in JavaScript without the need for the 'new'

After watching the Douglas Crockford video on JavaScript, one thing that caught my attention was his explanation of what happens when you forget to use new for a class. He mentioned that doing so would populate the global namespace, which in the browser is ...

In Vue2, you can utilize $ref to retrieve information from a child component and transfer it into the parent component's data

Trying to access child components' data in Vue2 and move it into the parent component's data without triggering an event. Saving count:20 from the child component into the parent component in the example below. Please let me know if there are any ...

How does Jasmine compare to the second parameter with the toBeCloseTo function?

Jasmine's documentation is often brief, but not always sufficient. I am curious about the second parameter of the toBeCloseTo function. The official reference only provides this example: it("The 'toBeCloseTo' matcher is for precision mat ...

Having difficulty kicking off a fresh React project on Windows

I've encountered an issue while setting up my React application on Windows OS. After running npm start, the application fails to load on localhost:3000, showing the error message Cannot GET /. Below is the project structure: - webpack.config.js - p ...

What is the abbreviated term for personalized elements in React Native development?

After discovering that custom components can be created like this: const CustomComp=()=>{ console.log('Created custom comp'); return(<View></View>); } export default function App(){ return(<View style={{flex:1}}> &l ...

How can the angular2 Polyfill js file be utilized?

What configuration files are necessary to integrate an Angular 2 application? ...

Why am I not achieving the desired code coverage in Jest while testing Angular?

I've recently developed a small project to monitor coverage results, but I'm encountering some unexpected issues. It seems like there's a configuration mistake on my end, but I'm struggling to identify what adjustments need to be made t ...

Utilizing the parameter "error" to distinguish unsuccessful tasks within async.mapLimit

In my coding process, I am using async.mapLimit to implement some parallel operations on an array with a limit of 10: async.mapLimit(files, 10, function(file, callback) { ... etc... }, function(error, files) { ... etc.. }); Within the main opera ...

Sort columns using drag and drop feature in jQuery and AngularJS

Utilizing the drag and drop feature of jquery dragtable.js is causing compatibility issues with AngularJs, hindering table sorting functionality. The goal is to enable column sorting by clicking on the th label and allow for column rearrangement. Currentl ...

Easy jQuery Mobile and AJAX login solution

My current project involves creating a mobile app with user login capabilities using PhoneGap, jQuery Mobile, AJAX, and PHP. I am starting with a basic HTML and PHP structure as I am not an experienced programmer, but even my simple user login form is not ...

When I declare a second service in the constructor, my modal service no longer opens as expected

Recently, I came across this login method in Angular: email: string = ""; password: string = ""; login() { const credentials = { email: this.email, password: this.password }; this.userService.login(credential ...

In Javascript, we can increment the current date by utilizing the `getDate()`

I am trying to create an if statement in JavaScript; if (nextProcessingDate > today ) { //do something } nextProcessingDate has a timestamp assigned, like 09/07/2014 12:10:17 To assign today's timestamp to the today variable, I am using this c ...

Integration of HostConfig with AdaptiveCards

Is there anyone familiar with incorporating a HostConfig to style AdaptiveCards using the webchat CDN in an Asp.Net Core environment? For instance, what should be the name of the file? And where exactly does it need to be placed? The specific setup for ...

Perform batch updates on multiple documents using MongoDB

How can I efficiently update multiple documents in MongoDB by iterating through an array of objects and then returning the modified documents in the response? Be sure to refer to the code comments for guidance .put(function (req, res) { var data = r ...

Having trouble getting my angular form validation to function properly

Even though I disabled Bootstrap's validation while using Angular, the validation for every input field still doesn't work. It seems like I have everything set up correctly. My code looks like this below with no success on input validation: < ...