如何在Angular中触发文件上传输入?

时间:2018-01-25 13:35:34

标签: angular

如何在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();
}

3 个答案:

答案 0 :(得分:14)

  1. 创建文件上传输入:

    setTitle(null)
  2. 创建一个按钮以触发对文件输入的单击:

     <input hidden type="file" #uploader
                       (change)="uploadFile($event)"/>
    
  3. 然后在您的组件中,您可以使用<button (click)="uploader.click()"> Upload </button>

    $event

答案 1 :(得分:0)

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)

传递给帖子调用的第三个参数是使用我们订阅的事件来跟踪上传进度

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

答案 2 :(得分:0)

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

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