Dynamically submitting a file upload form in IE10

2019-02-19 07:36发布

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-submits the form when a file has been selected

The original solution was something like this JSFiddle, where you have a link that loads the file dialog, then listens for the dialog's change event to auto-submit the form:

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

$("#my-nice-looking-button").on("click", function (e) {
    e.preventDefault();
    // load file dialog
    $("input[type=file]").trigger("click");
});

If you try that fiddle, it will work in IE9, Chrome, Firefox, etc., but it doesn't work in Internet Explorer 10. All the JavaScript functionality works, including the form's submit event getting fired. But, the browser never POSTs the form data to the server; it just sits there.

Is there some security safeguard or file upload limitation built into IE10 that prevents this from working?

1条回答
Anthone
2楼-- · 2019-02-19 07:43

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.

查看更多
登录 后发表回答