23

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

3 Answers 3

73
  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
}
Sign up to request clarification or add additional context in comments.

2 Comments

working fine your code, but i am trying instead of button on div only because within the div i showing user selected png file, so again if i try to move or cropping the image means its trigger the function. so how to prevent this scenario.
I don't know but in my case file selector open twice, any idea ?
6

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) {
    const uploadData = event.target.files[0];
    this.http.post('url', uploadData, {
        reportProgress: true,
        observe: 'events'
    }).subscribe(event => {
        console.log('uploaded successfully');
    });
}

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.