【问题标题】:How to trigger the file upload input in Angular?如何在 Angular 中触发文件上传输入?
【发布时间】:2018-01-25 13:35:34
【问题描述】:

Angular 4中如何触发文件上传输入?我正在尝试,但它不起作用。

我必须点击 div 并触发输入类型按钮,而不是输入按钮。

app.html:

<input id="custom-input" type="file" > 
<div (click)="myEvent(custom-input)">
    Click here to upload file
</div>

app.ts:

myEvent(event) {
    alert("event");
    event.nativeElement.click();
}

【问题讨论】:

    标签: angular


    【解决方案1】:
    1. 创建文件上传输入:
    <input 
        hidden 
        type="file" 
        #uploader
        (change)="uploadFile($event)"
    />
    
    1. 创建一个按钮来触发对文件输入的点击:
    <button (click)="uploader.click()">
        Upload
    </button>
    

    然后在你的组件中你可以使用$event:

    uploadFile($event) {
        console.log($event.target.files[0]); // outputs the first file
    }
    

    【讨论】:

    • 工作正常你的代码,但我尝试而不是 div 上的按钮只是因为在 div 中我显示用户选择的 png 文件,所以如果我再次尝试移动或裁剪图像意味着它触发功能.那么如何防止这种情况发生。
    • 我不知道,但在我的情况下,文件选择器打开两次,知道吗?
    【解决方案2】:

    HTML 模板 (attachment.component.html)

    <input 
        style="display: none" 
        type="file" 
        multiple 
        (change)="onFileChanged($event)" 
        #fileInput
    />
    <input 
        type="button" 
        class="upload-button" 
        value="Upload attachment(s)" 
        (click)="fileInput.click()" 
    />
    

    Typescript 中的处理(attachment.component.ts)

    为 post 调用传递的第三个参数是使用我们订阅的事件跟踪上传进度

    onFileChanged(event) {
        this.selectedFile = event.target.files[0];
        this.http.post('url', uploadData, {
            reportProgress: true,
            observe: 'events'
        }).subscribe(event => {
            console.log('uploaded successfully');
        });
    }
    

    【讨论】:

      【解决方案3】:

      您可以改为使用 标签来设置按钮样式

      app.html

      <label id="custom-input">
             <input type="file" (click)="myEvent(custom-input)" hidden multiple />
             Click here to upload file
      </label>
      

      app.ts

      uploadFile($event) {
          console.log($event.target.files[0]); // outputs the first file
      }
      

      但是,☝️ 这个函数将不起作用,因为它需要 异步 来等待用户的输入。

      private checkUpload: any;
      
      uploadFile(event) {
        // Check if file has been uploaded
        this.checkUpload = setInterval(() => {
          const checkFile = event.target.files[0];
          if (checkFile) {
            this.processFile(event);
          }
        }, 500);
      }
      
      // Runs after user uploads file;
      processFile(event) {
        clearInterval(this.checkUpload);
        const fileInput = event.target.files[0];
      }     
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-11-30
        • 2017-02-03
        • 1970-01-01
        • 2014-04-25
        • 2021-05-23
        • 2019-06-12
        • 1970-01-01
        相关资源
        最近更新 更多