简体   繁体   中英

How to open the file upload dialog in javascript

I have a problem in my webform project and here is an example code to describe it:

<input type="file" id="btnfile" style="display: none"/>
<span onclick="uploadFile()">UploadFile</span>
<script>
    $(function() {
        uploadFile(); //file dialog not open
        $("#btnfile").click(); //file dialog not open
    });

    function uploadFile() {
        $("#btnfile").click(); //file dialog will open by clicking the span
    }
</script>

I want my page to open the upload file dialog automatically when it is ready, and I use a function " uploadFile() " to "click" the fileupload input in the $() , but the function dosen't work unless it is called by an event,like clicking the span above.

  • Why the uploadFile() can't open the file dialog in $() ?
  • And is there any way to open the upload file dialog automatically?

Thanks.

For the sake of security, this behavior cannot be all done programmatically.

You can ask the user to install a plug-in or accept a signed applet to accomplish the work that cannot be done programmatically by default.

For Microsoft browsers, possibly use a ActiveX component which is supported in most versions.

In Firefox, you can write an add-on and ask the user to install it. Firefox add-ons are developed with javascript, it is easier than NPAPI or XPCOM for the web developers.

Google Chrome are going to eliminate NPAPI and are developing PPAPI.

Anyway, you can do that as long as the user accepts an extra component.

Another way is to find a security hole of a specific browser, please let me know if you found.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM