【问题标题】:How can I get the reference of a file through the HTML's input tag? (Angular 2)如何通过 HTML 输入标签获取文件的引用? (角度 2)
【发布时间】:2017-09-03 07:19:06
【问题描述】:

我想在 Firebase 中上传一张图片。但要做到这一点,我必须先获取文件。例如,如何通过 HTML 获取计算机的图像?我正在尝试这样做,但我不知道这样做的回报是什么。帮帮我……

<input type="file" name="image" [(ngModel)]="myImage">

【问题讨论】:

    标签: html angular firebase web


    【解决方案1】:

    您可以使用ElementRef 引用DOM 元素,然后从元素引用中提取上传文件的数据。使用#variableName 引用文件输入。

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

    在您的组件类中,使用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]; 
    
      }
    }
    

    我创建了一个示例 plunker here。

    【讨论】:

    • 太棒了!非常感谢!
    • 不需要注入viewchield。只需将事件传递给更改函数,然后使用 event.srcElement.files[0] 访问文件
    【解决方案2】:

    为什么不使用带有更改事件的指令?

    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);         
      }
    
    }
    

    不要忘记将指令添加到您的模块中。

    【讨论】:

    • 这看起来像一个更清洁、更可重复使用的解决方案
    猜你喜欢
    • 2016-08-30
    • 2019-06-12
    • 1970-01-01
    • 2019-03-09
    • 2018-04-23
    • 2017-08-29
    • 2017-08-13
    • 2020-06-20
    相关资源
    最近更新 更多