Tips for retrieving the file value with ng2-file-upload in Angular by clicking a button

In this scenario, I am configuring a file upload feature using ng2-file-upload where users can drop files into the designated area. At present, I am able to capture the values of the dropped files successfully. However, I encounter an issue as I also want to retrieve the uploaded file value by triggering a button click function. How can I accomplish this? Below is the code snippet:

Please note that I need to access the fileList value.

Currently, I am able to obtain the file list values using the filedropped method, but additionally, I require the ability to fetch the value by clicking a button.

import { Component } from '@angular/core';
import { FileUploader } from 'ng2-file-upload';

const URL = 'https://evening-anchorage-3159.herokuapp.com/api/';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  // Initialization of variables and constants
  
  public uploader:FileUploader = new FileUploader({url: URL});
  public hasBaseDropZoneOver:boolean = false;
  public selectedFilesArray = [];
  private selectedFile;

    // Methods for handling file selection, hover effects, etc.

  public selectFile(e: any): void {
    // Implementation logic
  }

  public fileOverBase(e: any): void {
    // Implementation logic
  }

  public selectAllFiles(e: any): void {
    // Implementation logic
  }

  public fileDropped(fileList: any): void
  {
    // Logic for handling dropped files
  }

  public fileChecked(e: any): void {
    // Logic for handling checked files
  }

  // Method to retrieve file information
  getInfo(){
    console.log('file info');
  }

}

Find the live demo at this URL.

https://i.sstatic.net/DK07M.png

Answer №1

Note: The author of this post has made an edit to accommodate the request of having File objects available within the scope of the component.

Instead of storing just the name property, it is recommended to store the entire File object. To do this, change the fileSelectState to an array (or use a different class member for this) and modify the fileDropped() method as follows:

public fileDropped(fileList: any): void
  {
    for(var i =0 ; i< fileList.length; i++){
        this.fileSelectState.push(fileList[i]);
    }

  }

If you are not required to support IE, consider replacing the for loop with:

this.fileSelectState = Array.from(fileList);

Additionally, update the getInfo() method from logging 'file info' to logging the fileSelectState itself:

getInfo(){
  console.log(this.fileSelectState);
}

Whenever you need to access the file name, refer to it using:

this.fileSelectState[0].name

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

Utilizing the Docker COPY command to exclusively transfer files of a specific file type extension

I have been working on implementing a new build process for one of our Angular applications. In order to reduce the bundle size, I have included a build step that involves gzipping all the files in the dist folder after the build process. After the build, ...

When the localStorage is empty, populate it with data from a JSON file

const username = document.querySelector("span.username").textContent; if (localStorage.getItem(username) === null) { //user data not found, start setting //localStorage.setItem(username, JSON.stringify(userA)); console.log("localstorage for " ...

Choose a selection from the options provided

This is a sample for demonstration purposes. I am trying to display an alert with the message "HI" when I click on Reports using the id main_menu_reports. My attempted solution is shown below. <ul class="nav" id='main_root_menu'> & ...

What is the process for updating data for THREE materials?

Is it possible to update the material of an object based on a radio button selection? I have managed to change the color in my current example, but the entire material does not get updated. How can I instruct THREE to adjust its internal data accordingly? ...

Unable to retrieve an image file from my Node.js server using my frontend application, which are both independent of each other

I am currently running my nodejs backend on localhost:8080 and frontend on localhost:8081 using http-server. I am facing an issue where I am unable to download a file from the server side to the client side. Since I am new to node js, I am encountering som ...

Local host's attempt to retrieve data from an external site via an Axios GET request was rejected

I'm currently attempting to execute a GET request on an external website in order to scrape some information. Unfortunately, my axios GET request is returning a connection error. I suspect that this issue may be related to the fact that I am sending t ...

What is the best approach to managing data organization within a websocket API?

We currently have a ReactNative page that displays live data using a Websockets based API. We want to provide users with the option to sort the data based on their selected field. What is the best way to implement data sorting? I am considering two possi ...

Utilize DomSanitizer to add custom styles to elements using classes in Angular

<div [innerHtml]="someHtml | safeHtml"></div> someHtml = '<span class="fas fa-calendar" style="font-size:15px"></span>' By utilizing the innerHtml property, I am able to inject a html element and apply inline styles thro ...

Modifying the text of a material UI button depending on a particular condition

I have a component that uses the Material UI button, and I need to change the text of the button based on a condition. If the order amount is 0, I want it to display "cancel", otherwise, it should show "refund". Can someone guide me on how to achieve thi ...

Tips for managing asynchronous code that invokes other asynchronous code in AngularJs

My factory utilizes indexedDB and a method called getRecipe that relies on this indexed db to fetch data. The issue arises because indexedDB returns its instance in an asynchronous call, and getRecipe is another method that also returns its value asynchro ...

Setting the initial values of state variables upon rendering of a component and using custom hooks

I have a file called Body.jsx that handles fetching data from an API and filtering it. In an attempt to clean up the code, I created a custom hook named useResData specifically for fetching data: export const Body = () => { const resDataList = useResD ...

Invoke a PHP function within the current file

One thing I'm wondering about is whether it's possible to call a php query from within the same file. Let me show you the code I have: <?php function aggiungiPagine(){ global $conn; header('Access-Control-Allow-Origin: *&apos ...

Can you provide me with the sequelize query that is equivalent to this raw query?

Retrieve the ID from the offers table where the user ID is not equal to '2' and the ID is not present in the list of notified offers for user '2'. ...

How can you merge two promises while preserving their execution order and data flow seamlessly?

Two promises are at play here: Promise 1 resolves to an array of objects, while Promise 2 creates multiple files, writes to them, and resolves to a boolean value indicating success based on the array from Promise 1. The sequence of execution is as follows ...

Can a function return another function?

As I delve into my Javascript learning journey, I encountered a puzzling Sa() function within this code snippet. Initially, I deemed it to be an unsolvable problem like the Kobayashi Maru, but upon closer inspection, I suspect that this Sa() function migh ...

Step-by-step guide to setting up a customer account and adding a credit card with Stripe in an Angular Node application

I've been struggling to find a solution for creating a user and storing their credit card information in Stripe for the past day without success. After reviewing the documentation at: https://stripe.com/docs/api/customers/create const stripe = requir ...

After completing a sequence, it does not reset

I'm working on creating a versatile "slideshow" feature that can be used for various elements. Currently, I am testing it on a div that contains paragraph text taken from my HTML document and represented as container1, container2, and container3. The ...

You cannot assign a constructor type that is abstract to one that is not abstract

I am attempting to create an abstract component in Angular, but I am encountering the following error: Error: src/app/app.module.ts:191:5 - error TS2322: Type 'typeof AbstractFormComponent' is not assignable to type 'any[] | Type<any>& ...

Error message in Angular 2: Deletion operation is restricted

I am encountering an issue with the Angular 2 http.delete method. Below is my code snippet: const headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'}); this.http.delete(ConstVarService.url + 'api/tasks/Usu ...

Error in the data format or configuration within the chart.js streaming data plugin

I'm in the process of setting up a live streaming data chart that reads data from a page displaying the most recent data points every second. I am utilizing the chart.js-plugin-streaming plugin developed by nagix for this task. The challenge I'm ...