Angular 2 FileReader: A comprehensive guide

I have a situation where I need to upload an image in section X and pass the base 64 data of the uploaded image to section Y. But I am encountering some difficulties in section X

HTML:

<input type="file" id="hotspot" (change)="uploadHotSpot($event)">

TS File:

 uploadHotSpot($event){
    var file:File = $event.target.files[0]; 
    var reader:FileReader = new FileReader();

    if (file) {
      reader.readAsDataURL(file); //reads the data as a URL
      this.pin = reader.result;
      console.log(this.pin);
    }
}

Issue: I am able to successfully see the base 64 data in the console log when uploading the image with the developer tools open. However, when I close the debugger tool and try to upload the image again, the console.log is coming out blank... Any thoughts on this?

Answer №1

Since that's not how it operates. It is necessary to set up an onload callback in order to receive the outcome. Here's an example:

handleUpload($event) {
    var file:File = $event.target.files[0]; 
    var reader:FileReader = new FileReader();

    reader.onload = () => {
      this.pin = reader.result;
      console.log(this.pin);
    };

    if (file) {
      reader.readAsDataURL(file); //reads the data as a URL
    }
}

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

Populate Input Field Based on Dropdown Selection

My goal is to retrieve the value of "hargaJual" when I choose an option. However, when I add a new row to the table and select a different option, only the first row's "Harga" value changes while the second row remains empty. Take a look at the outco ...

Designing a user interface that consists of numerous distinct components

Challenge I'm faced with a dilemma regarding site A, which is built using React. Specifically, I need to find a way to integrate smaller React components into site A whenever a user navigates to a specific page within the site. Each of these smalle ...

Error TS2339: The 'phoneType' property cannot be found on the 'Object' data type

Below is the declaration of an object: export class Card { private _phones:Object[] get phones(): Object[]{ if(this._phones === undefined) this._phones = [] return this._phones } set phones(val:Object[]){ ...

Is the Javascript Browser Plugin currently activated?

I am currently experimenting with Google Earth and I'm trying to figure out whether the Browser Plugin for Google Earth is Enabled or not (Please note: Scenarios such as the Plugin being installed but deactivated). This is my plan on how to achieve t ...

Issue with Vue3 Button - property error not defined

I'm currently facing an issue with a button that isn't functioning as expected in the screenshot provided. I'm hopeful that someone can assist me with this. Button functionality The button itself is not clickable, but I am able to submit t ...

The Javascript navigation bar is not displaying properly on mobile devices as it should

After customizing the responsive navbar tutorial from W3Schools using CSS and JS, I encountered an issue. I wanted to include a logo and a web page title before the navbar, which worked perfectly when the webpage was maximized. However, when I resized the ...

Inject JavaScript Object Information into Bootstrap Modal

After iterating through each object and assigning its data to an individual div along with a button, I encountered an issue. When testing the buttons, I noticed that only the last object's data was displayed in all of the modal windows. Any suggestion ...

Obtain data without issuing a new query in flexigrid

I am encountering an issue with flexigrid where the initial page load triggers a query, and then when I either (1) adjust the sort order or (2) navigate to the next page, it runs a new query with different parameters, resulting in slow performance. I am s ...

Using AJAX to upload jQuery file - sharing PHP variables

After setting up the blueimp jQuery file upload, I've encountered a problem that's stumping me. My goal is to retrieve a PHP variable that's posted when the file is uploaded and execute some PHP code if it exists. I have made modifications ...

Using three.js to set the HTML background color as clearColor

How can I set the HTML background as clearColor using three.js? Here is the code snippet for three.js: // Setting up the environment var vWebGL = new WEBGL(); var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(75, window.innerWidth / ...

Is it possible to access the ID of a collection_select and have a list of items appear whenever the selection is modified?

I am working on a form named _form.html.erb <%= simple_form_for(@exam) do |f| %> <%= f.error_notification %> <div class="field"> <%= f.label :Year %> <%= f.collection_select :year_id, Year.order(:name), :id, :name, ...

Consistently directing to a single page on the Node Js web server

I'm in the process of creating a website with multiple HTML pages. Currently, I have code that successfully links to the login page, but unfortunately, the localstores page also directs to the login page. const express = require('express') ...

extract the key identifier from the JSON reply

My JSON ResponseData example for form0 is provided below: { "MaterialType": "camera", "AssetID": 202773, "forms": [ { "release": "asyncCmd/accessCameraMulti", "action": "rest/Asset/202773/cameraAccessMultiple", ...

Updating Data with Ajax in Laravel

Hey there, could you walk me through the process of updating with Ajax? I'm working with Laravel I prefer using HTML and Ajax only Here are my routes: Route::post('/post/homepage', 'AdminController@HomePage'); ...

Invoke the function for every element during the mapping process

I am attempting to call a function in React Native maps for each element. This function will randomly determine properties of the rendered component, making sure that each component is unique. The renderComponent function takes an argument called item as w ...

I need to retrieve the Instagram follower count for a specific user using JavaScript based on their user ID

I'm looking to design a form that allows users to input their Instagram ID and receive the exact number of followers without the "k" abbreviation. However, I am unsure how to achieve this. Any guidance on how to accomplish this would be greatly apprec ...

Quicker Solution to Iteration in Google Apps Script with JavaScript

I've set up a for loop to extract sales data from an array (salesLog) and transfer it to a designated sheet (targetSheet) in columns. The sales data is spread across multiple columns in the array. The loop adds up the columns between columnStart and c ...

Cameras within the boundary of an A-frame restricted by distance

I'm trying to implement a code that restricts the camera movement in A-frame. The current functionality teleports the camera back to the position 0, 1.6, 0 when it moves 10 spaces away from the starting point on the x or y axis. However, I want to mod ...

THREE.js - Transformative Vertex Shader for Billboards

I am trying to figure out how to make an instance of THREE.Mesh always face the camera using a vertex shader instead of just relying on the [THREE.Mesh].lookAt() method. After reading through NeHe's Billboarding tutorial, I understand the concept exc ...

Tips for limiting the frequency of Angular provider loading instances

I have created a provider (I tried with a controller as well, but got the same results). Here is my code: .provider('socketio', function() { this.socket = io.connect("//localhost); console.log("LISTENING..."); this.$get = function() ...