Home > Back-end >  How to make an open file dialog show when user click on the icon image?
How to make an open file dialog show when user click on the icon image?

Time:08-09

How can I make open file dialog show when user click on the icon image. I've tried to put input "" but it add button by default any way to make this button invisibleenter image description here.

CodePudding user response:

Not an elegant solution, but you can insert a hidden file type input in the DOM and mock a click on it.

Somewhere in your html (I would put it right next to the image icon):

<input id="fileInput" type="file" style="display: none" />

And then in your JS:


imageIcon.addEventListener('click', () => {
  const input = document.getElementById("fileInput");
  input.click();
})

CodePudding user response:

Here's a Javascript solution:

const openFileButton = document.getElementById("openFileButton");

async function askUserForFiles(multiple = false, timeout = 10) {
  const input = document.createElement("input");
  input.type = "file";
  input.multiple = multiple;
  input.click(); // "click" the file picker button

  return new Promise((resolve, reject) => {
    input.addEventListener("change", event => resolve(input.files));
    setTimeout(()=>reject(), timeout * 1000); // After the timeout runs out, give up waiting for the user to choose
  });
}

openFileButton.addEventListener("click", async event => {
  try {
    const fileList = await askUserForFiles(true, 20); // Allow multiple files, and wait for 10 seconds before error.
    alert(`${fileList.length} files selected`);
  }
  catch (e) {
    alert("Timed out.");
  }
});
<button id="openFileButton">Click Here!</button>

  • Related