Opening hidden file <input> from a toolbar button

Hello everyone!

I’m developing a PWA with ionic and I have spent the last couple hours searching the web to figure out how to achieve this. I’m aware that a file dialog can only be opened from javascript when it is user initiate, but I’ve tried everything I can think of and still can’t get it to work. I’m doing this so a user can upload a profile picture by clicking on the photo in the center of the profile page. I obviously don’t want an ugly input box.

If anyone has experience with this I’d love to hear from you. Most of the examples I’ve seen use jquery, but I don’t see why it couldn’t be done with plain javascript. I’d also rather not have to use jquery in my project just for this single issue.

Thank you so much!
Chris

Edit: I just noticed that I said I’m trying to do it from a toolbar button in the title and the profile picture in the body of the post. I’d prefer the profile picture method, but I’ve been trying to achieve it from the toolbar. I’m thinking it should work the same for either scenario, since both are user initiated clicks.

You mentioned “plain javascript”. I’m going to assume that means you’re trying to use Ionic without a framework such as Angular. Personally, I can’t stand JavaScript and therefore do everything in my power to shield myself from its infernal bletchery (such as using frameworks like Angular). Therefore, I apologize in advance if this breaks every rule of how one is supposed to write frameworkless Ionic apps, but hopefully you will find something useful in it nonetheless:

<ion-button onclick="document.querySelector('#uploader').click()">pop file chooser</ion-button>
<input type="file" id="uploader" hidden>

1 Like

Actually, I am using Angular 8, but I assumed it would be a strictly javascript solution. I will give this a try, but if you have an angular solution, I’m all ears. Thank you.

Thank you so much. Your code worked great. I was using an ion-input for some strange reason and that was the issue. Wouldn’t have figured it out without your code.

<ion-button (click)="popFileChooser()">pop file chooser</ion-button>
<input type="file" #uploader hidden>
@ViewChild("uploader", {static: true}) uploader: ElementRef<HTMLInputElement>;

popFileChooser(): void {
  this.uploader.nativeElement.click();
}
1 Like