简体   繁体   中英

How to trigger the file upload input in Angular?

How to trigger the file upload input in Angular 4? I'm trying, but it's not working.

Instead of input button, I have to click on div and trigger the input type button.

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();
}
  1. Create the file upload input:
<input 
    hidden 
    type="file" 
    #uploader
    (change)="uploadFile($event)"
/>
  1. Create a button to trigger a click on the file input:
<button (click)="uploader.click()">
    Upload
</button>

Then in your component you can use the $event :

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

HTML Template (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()" 
/>

Handling in Typescript(attachment.component.ts)

Third argument passed for the post call is for tracking the progress of upload using the event which we get subscribe to

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

You could instead use a label to style the button .

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
}

However, ☝️ this function will not work as it needs to be asynchronous to await the user's input.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM