Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger the file upload input in Angular?

Tags:

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();
}
like image 643
dhana Avatar asked Jan 25 '18 13:01

dhana


People also ask

How can you tell if a file is canceled and clicked on input?

The easiest way is to check if there are any files in temporary memory. If you want to get the change event every time user clicks the file input you can trigger it. Show activity on this post. In my case i had to hide submit button while users were selecting images.

How can I limit the size of attachment file upload in angular?

You can restrict the maximum allowed file size (in bytes) by using the maxFileSize property. If the selected file exceeds the maximum size, an error message will be displayed.


Video Answer


2 Answers

  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
}
like image 155
TheUnreal Avatar answered Oct 17 '22 17:10

TheUnreal


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');
    });
}
like image 37
Sriram Kumar Avatar answered Oct 17 '22 17:10

Sriram Kumar