开发者

How to open file upload prompt when text link is clicked?

This works in FF6 and IE 7, 8 and 9, but not Chrome/Safari or Opera:

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>

    <script type="text/javascript">
        $(function() {

            $('#uploadFile').click(function(e) {
                $('#fileUploadField').click();
                e.preventDefault();
            });

        });
    </script>

    <input type="file" name="something" style="display: none" id="fileUploadField" />
    <a href="" id="uploadFile">Upload File<开发者_运维问答/a>

I'm guessing this is due to browser security restrictions. Does anyone know of any cross browser solution to achieve this?


You can't invoke click on a hidden element, it's a security restriction. Instead of display: none, use opacity: 0 instead. That seems to work.

Here's a fiddle. I see the file selection dialog with FF6 on Win 7, Chrome 13 on Win 7/Mac OS X 10.6.8 and Safari 5 on Mac OS X 10.6.8


Even if there is no "display:none" it won't work in IE8. As soon as you click submit, IE8 will delete the data in the file-input field and doesn't submit the form. Try following code as php:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>IE8-Test</title>
    <script type="text/javascript" src="js/jquery-1.6.4.min.js"></script>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <script type="text/javascript">
      $('#btn').live('click', function(){
        $('#file').click();
      })
    </script>
  </head>
  <body>
    <form action="test.php" method="POST" enctype="multipart/form-data">
      <input id="file" type="file" name="image" class="image"/>
      <div id="btn">Click me to do a js click on the input type=file button.</div>
      <input id="submit" type="submit" name="formsubmit" value="Upload"/>
    </form>
    <br/>
    <br/>
    <br/>
    <?php
      if(isset($_POST['formsubmit'])){
        echo '<div>POST-Data</div>';
        echo '<pre>';
        var_dump($_POST);
        var_dump($_FILES);
        echo '</pre>';
      }
    ?>
  </body>
</html>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜