Search code examples
typescriptinput-type-file

Why I cannot open file dialog with typescript faking <a> link for <input type=file>


Here's my situation, code and reference from Stackoverflow.

I want to trigger open dialog and I found references but they don't seem to work;

First my code snippet:

                <i class="fas fa-upload uploadicon"></i><br>
                Drop document here or 
                <a href="javascript:;" class="dropimgmessage" id="uploadLink" name="uploadLink" ngbTooltip="Click to upload a document or drag here!" placement="top">browse</a>
                <input type="file" class="form-control fileuploader" #fileInput  id="api-file-container" formControlName="docUpload" name="api-file-container" (change)="handleFileInput($event.target.files)">
                <span class="dropimagetypemsg">Supports PDF, JPG, PNG, GIF</span>

Now my typescript:

declaration of variables:

public uploadlink: HTMLElement;
public fileinput: HTMLElement;

------

ngAfterViewInit() {

    this.uploadlink = document.querySelector('#uploadLink') as HTMLElement;
    this.fileinput = document.querySelector('#api-file-container') as HTMLElement;

    this.uploadlink.addEventListener('click', (e: Event) => {
      e.preventDefault();
      this.fileinput.click();
    });

}  

What happens is that the code fires, but never goes into the fragment:

this.uploadlink.addEventListener('click', (e: Event) => {

it stops at the .addEventListener.

So I tried to call a function onClick from the HTML like so.

public fakeFileInput(e: Event): void {

    console.log('Fake Input to File Upload: ', e);
     if(this.uploadlink.getAttribute('text') === 'browse') {
       console.log('EVENT browse upload was click: ');
       this.uploadlink.setAttribute('defaultPrevented', 'false');
       this.fileinput.click();
     }

}

by adding that call to the function like so:

<a href="javascript:;" (click)="fakeFileInput($event)" class="dropimgmessage" id="uploadLink" name="uploadLink" ngbTooltip="Click to upload a document or drag here!" placement="top">browse</a>

Now that works, but, I get an error here: File chooser dialog can only be shown with a user activation.

My References:

Calling a typescript method from your html button onclick event

How to open a file / browse dialog using javascript?

How to make a link act as a file input

And on JSFiddle - http://jsfiddle.net/7aGEv/3/

So, where am I going wrong?

Thank you.


Solution

  • You don't need any JS to trigger a file upload without a button, you can simply use a label for that:

    <label for="uploadInput">browse</label>
    <input id="uploadInput" type="file" style="display:none" />