Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

421
Visualizações
How can I get the reference of a file through the HTML's input tag? (Angular 2)

I want to upload an image in Firebase. But to do that I have to get the file first. How can I get an image of my computer, for instance, through the HTML? I'm trying to do this, but I don't know what's the return of this. Help me guys...

<input type="file" name="image" [(ngModel)]="myImage">
about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You can reference the DOM Element using ElementRef and then extract the data of the file uploaded from the element reference. Use #variableName to reference the file input.

<input #fileInput (change)="fileUpload()" type="file" name="pic" accept="image/*">

In your component class, reference the file input using ViewChild.

import {Component, ElementRef, Renderer2, ViewChild} from '@angular/core'
@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>{{name}}</h2>
      <input #fileInput (change)="fileUpload()" type="file" name="pic" accept="image/*">
    </div>
  `,
})
export class App {
  name:string; 
  @ViewChild('fileInput') el:ElementRef;
  constructor(private rd: Renderer2) {
    this.name = `Angular : File Upload`
  }

  fileUpload() {
    console.log(this.el);
    // Access the uploaded file through the ElementRef
    this.uploadedFile = this.el.nativeElement.files[0]; 

  }
}

I have created a sample plunker here.

about 4 years ago · Santiago Trujillo Relatório

0

Why don't you use directive with change event?

component.html

<input type='file' uploader accept=".txt,.doc">

uploader.directive.ts

import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[uploader]'
})
export class UploaderDirective {

  @HostListener('change',['$event.target.files'])
  onChanges(files) {
    this.readFile(files[0])
  }

  readFile(file){
    let fileReader = new FileReader();
    fileReader.onload = async (e: any) => {
      //DO SOMETHING HERE with e.target.result            
    }
    fileReader.readAsText(file);         
  }

}

Don't forget to add the Directive to your module.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda