Dynamically submitting a file upload form in IE10 using jQuery

前端 未结 1 1124
再見小時候
再見小時候 2021-01-14 11:05

I have a form whose only purpose is to upload files, but for user experience reasons, I need a nice-looking button that:

  1. loads the file dialog
  2. auto-su
相关标签:
1条回答
  • 2021-01-14 11:36

    As it turns out, yes, IE10 does not let you both programmatically load a file dialog and automatically submit a form after a change event on a file dialog. Presumably one or the other will work, but not both. I haven't found any documentation to support this claim other than my own experimentation.

    The solution I found was to use CSS to style the file dialog's button such that it was invisible, but laid over the top of the nice-looking button, so that when you think you're clicking on the button, you're actually clicking on the file dialog's "select" button:

    input[type=file] {
        /* positioning strategies will vary depending on design */
        font-size: 25px;
        position: relative;
        top: -50px;
        left: -10px;
    
        /* make it invisible! */
        opacity: 0;
    
        /* make the cursor act like it's hovering over an anchor tag */
        cursor: pointer;
        cursor: hand;
    }
    

    Then you just need to listen for the change event and submit the form as before:

    $("input[type=file]").on("change", function () {
        // auto-submit form
        $("form").submit();
    });
    

    Doing this means that you are "organically" loading the file dialog, and IE10 lets it happen and allows you to auto-submit the form.

    This solution also works in WebKit and Firefox.

    0 讨论(0)
提交回复
热议问题