32

I am new in php. I have a form on which i place a button Value as Upload MB when user click on this button it redirects on a web form where i place a file upload control and user upload file here. Here is image

button

After clicking this button user redirect on this form

upload form

here user upload file.

MY QUESTION

Is it possible that can i make my button Upload Mb as file upload button? Can it works like file upload control button?

Actually i want to save user time. I want that when user click on Upload MB button it not redirects on Form. But when user Click on Upload MB button it allow to user to upload file and open browsing window. After that when user upload file it redirects on form.

Can you guys tell me it is possible or not?

sunny
  • 1,511
  • 5
  • 20
  • 57

6 Answers6

76

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>
Shrinivas Shukla
  • 4,325
  • 2
  • 21
  • 33
  • Shrinivas How it will redirect on form after upload file? – sunny Jul 29 '15 at 07:11
  • Check out this [fiddle](http://jsfiddle.net/shrinivas93/m0trsgct/2/). You just need to enclose your form controls inside `form` tag. – Shrinivas Shukla Jul 29 '15 at 07:25
  • did it carry file while redirection? – sunny Jul 29 '15 at 07:28
  • Absolutely, form submission transfers all the values to the server during redirection. On the server, these values can be accessed using their `name` attribute, `'filename'` in this case. – Shrinivas Shukla Jul 29 '15 at 07:30
  • 1
    But when i run this code in my browser as my php file upload button is not working – sunny Jul 29 '15 at 07:36
  • din not open browsing window\ – sunny Jul 29 '15 at 07:41
  • Check console for errors. If it is working on stackoverflow as well as on jsfiddle, then it should also work on your browser. There must be some error in the console. – Shrinivas Shukla Jul 29 '15 at 07:43
  • Can it is possible without using submit button i redirect user? – sunny Jul 29 '15 at 07:47
  • When user choose file then without clicking on submit button it redirect on form? – sunny Jul 29 '15 at 07:47
  • Check out this [fiddle](http://jsfiddle.net/shrinivas93/m0trsgct/3/). Use javascript to submit the form when user selects the file. No need to click **`"Submit"`** button – Shrinivas Shukla Jul 29 '15 at 07:52
  • Why all fiddle is not working when i paste it in my page? – sunny Jul 29 '15 at 07:55
  • Check for these 2 main reasons (1) There is **NO** `html` tag , `body` tag in fiddle. Add it before copying it to your code (2) Place the javascript part inside `script` tag in the `head` tag. – Shrinivas Shukla Jul 29 '15 at 07:59
  • `
    `
    – sunny Jul 29 '15 at 08:02
  • Check out my updated answer. [Here](https://jsbin.com/pabiyi/edit?html,output) is the entire code. – Shrinivas Shukla Jul 29 '15 at 08:19
11

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.

BananaAcid
  • 3,221
  • 35
  • 38
7

I would suggest to convert button to label. apply the css to label so that it looks like button.

e.g. -

        <input type="file" id="BtnBrowseHidden" name="files" style="display: none;" />
        <label for="BtnBrowseHidden" id="LblBrowse">
            Browse
        </label>
Prasad Shigwan
  • 520
  • 5
  • 14
  • 2
    This doesn't work from an accessibility standpoint - keyboard-only users will not be able to open your file input since the label cannot receive focus. Making the label into a button won't work either: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label#Accessibility_concerns. It's unfortunate because this is a really clean solution otherwise. – AJ Richardson Sep 11 '20 at 14:38
4

Bootstrap Way

.choose_file {
    position: relative;
    display: inline-block;   
    font: normal 14px Myriad Pro, Verdana, Geneva, sans-serif;
    color: #7f7f7f;
    margin-top: 2px;
    background: white
}
.choose_file input[type="file"]{
    -webkit-appearance:none; 
    position:absolute;
    top:0;
    left:0;
    opacity:0;
    width: 100%;
    height: 100%;
}
<div class="choose_file">
    <button type="button" class="btn btn-default" style="width: 125px;">Choose Image</button>
    <input name="img" type="file" accept="image/*" />
</div>
Anas Al Hamdan
  • 768
  • 1
  • 5
  • 18
2
 <html>
 <body>
 <input type="file" id="browse" name="fileupload" style="display: none" onChange="Handlechange();"/>
 <input type="hidden" id="filename" readonly="true"/>
 <input type="button" value="Upload MB" id="fakeBrowse" onclick="HandleBrowseClick();"/>
 </body>
 <script>
 function HandleBrowseClick()
 {
   var fileinput = document.getElementById("browse");
   fileinput.click();
 }

function Handlechange()
{
 var fileinput = document.getElementById("browse");
 var textinput = document.getElementById("filename");
 textinput.value = fileinput.value;
}
</script>
</html>
Salim Malik
  • 54
  • 1
  • 9
0

There's an experimental feature that does exactly what you are looking for. You can take a look at it here: https://developer.mozilla.org/en-US/docs/Web/API/Window/showOpenFilePicker

Bonifacio2
  • 3,405
  • 6
  • 34
  • 54