Search code examples
javascriptphpjqueryformsfile-upload

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


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?


Solution

  • 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>