0

So I want to to have a div tht accts like button/input with type file that can allow me to upload files, but I don't know how to do that.

I saw some anwsers but they where using Jquery but I want plain JS.

modih65067
  • 109
  • 1
  • 6
  • Can you include the code you have already tried so far that hasn't worked? – mike510a Feb 27 '22 at 12:02
  • Couldn't find anything to try – modih65067 Feb 27 '22 at 12:09
  • Does this answer your question? [How to open select file dialog via js?](https://stackoverflow.com/questions/16215771/how-to-open-select-file-dialog-via-js) – mike510a Feb 27 '22 at 12:12
  • I don't understand the part 'a `div` that acts like `button`/`input` with `type="file"`'. Why not just use a `button` or an `input`? The latter are specifically meant for user interaction/input, whereas the former isn't. Otherwise the answer provided by @mike510a looks solid. – Bumhan Yu Feb 28 '22 at 02:30

1 Answers1

0

Here's a ready-made solution that I found by typing your question into stack overflow's search bar..

function promptFile(contentType, multiple) {
  var input = document.createElement("input");
  input.type = "file";
  input.multiple = multiple;
  input.accept = contentType;
  return new Promise(function(resolve) {
    document.activeElement.onfocus = function() {
      document.activeElement.onfocus = null;
      setTimeout(resolve, 500);
    };
    input.onchange = function() {
      var files = Array.from(input.files);
      if (multiple)
        return resolve(files);
      resolve(files[0]);
    };
    input.click();
  });
}
function promptFilename() {
  promptFile().then(function(file) {
    document.querySelector("span").innerText = file && file.name || "no file selected";
  });
}
<button onclick="promptFilename()">Open</button>
<span></span>

Reference link: How to open select file dialog via js?

mike510a
  • 2,102
  • 1
  • 11
  • 27