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

dha*_*ana 9 angular

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

我不必输入按钮,而是单击div并触发输入类型按钮.

app.html:

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

app.ts:

myEvent(event) {
    alert("event");
    event.nativeElement.click();
}
Run Code Online (Sandbox Code Playgroud)

The*_*eal 23

  1. 创建文件上传输入:

     <input hidden type="file" #uploader
                       (change)="uploadFile($event)"/>
    
    Run Code Online (Sandbox Code Playgroud)
  2. 创建一个按钮以触发文件输入的单击:

    <button (click)="uploader.click()">
     Upload
    </button>
    
    Run Code Online (Sandbox Code Playgroud)

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

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


小智 6

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()" 
/>
Run Code Online (Sandbox Code Playgroud)

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

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

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