Is it Possible to make a button as File upload Button?

my 2 cents to the topic: all in code, no input needs to be added to the page.

function onClickHandler(ev) {
  var el = window._protected_reference = document.createElement("INPUT");
  el.type = "file";
  el.accept = "image/*";
  el.multiple = "multiple"; // remove to have a single file selection
  
  // (cancel will not trigger 'change')
  el.addEventListener('change', function(ev2) {
    // access el.files[] to do something with it (test its length!)
    
    // add first image, if available
    if (el.files.length) {
      document.getElementById('out').src = URL.createObjectURL(el.files[0]);
    }


    // test some async handling
    new Promise(function(resolve) {
      setTimeout(function() { console.log(el.files); resolve(); }, 1000);
    })
    .then(function() {
      // clear / free reference
      el = window._protected_reference = undefined;
    });

  });

  el.click(); // open
}
#out {
  width: 100px; height: 100px; object-fit: contain; display: block;
}

/* hide if it would show the error img */
#out[src=''] {
  opacity: 0;
}
<img src="" id="out" />
<button onClick="onClickHandler(event)">select an IMAGE</button>

Note: the el might get garbage collected, before you process all data - adding it to window.* will keep the reference alive for any Promise-handling.


You can keep a <input type='file' hidden/> in your code and click it using javascript when the user clicks on the "Upload MB" button.

Check out this fiddle.

Here is the snippet.

document.getElementById('buttonid').addEventListener('click', openDialog);

function openDialog() {
  document.getElementById('fileid').click();
}
<input id='fileid' type='file' hidden/>
<input id='buttonid' type='button' value='Upload MB' />

Here is the complete code.

<html>
    <head> 
        <script>
            function setup() {
                document.getElementById('buttonid').addEventListener('click', openDialog);
                function openDialog() {
                    document.getElementById('fileid').click();
                }
                document.getElementById('fileid').addEventListener('change', submitForm);
                function submitForm() {
                    document.getElementById('formid').submit();
                }
            }
        </script> 
    </head>
    <body onload="setup()">
        <form id='formid' action="form.php" method="POST" enctype="multipart/form-data"> 
            <input id='fileid' type='file' name='filename' hidden/>
            <input id='buttonid' type='button' value='Upload MB' /> 
            <input type='submit' value='Submit' /> 
        </form> 
    </body> 
</html>