IE clears input[type=“file”] on submit

2020-02-16 05:35发布

问题:

I have a page (demo):

    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
        <script type="text/javascript" src="http://codeorigin.jquery.com/jquery-1.10.2.min.js"></script>
        <script type="text/javascript">
            $(function() {
                $("#id_button").click(function(e) {
                    $("#id_file").click();
                });
            });
        </script>
    </head>
    <body>
        <form method="post" enctype="multipart/form-data" action="http://www.google.com/">
            <input type="file" name="file" id="id_file" />
            <input type="button" id="id_button" value="fake button" />
            <input type="submit">
        </form>
    </body>

</html>

if I open browse dialog via clicking "fake button", select file (I see it in input[type="file"]), than click submit button and no post happens, the input[type="file"] is cleared.

What should I changed to get it work?

I get this problem in IE8 and IE10.

PS: file input will be hidden, so user will work only with fake button.

回答1:

All of the browsers have different behavior when it comes to what they allow you to do from javascript with regards to programmatically clicking the input button for file inputs.

The best solution I have found that seems to work cross browser is to set the opacity to 0 (do not use display:none) and put the button underneath the input, so the user clicks through the 0 opacity input to your button, thus firing the input select dialog.

A good writeup on styling the file input can be found here: http://www.quirksmode.org/dom/inputfile.html



回答2:

http://jsfiddle.net/j38Wj Works fine in Google Chrome but does not work in IE 10. As I think IE does not allow select file by external 'click' event. Only one way to "customize" input[type=file] is usage of opacity style to hide it and relative positioning of custom button control below it. Working example: http://blueimp.github.io/jQuery-File-Upload/

[...]


回答3:

I think all browser does that behaviour for security reason. When you submit a form, you are redirected to a different page(or the same page) and if you are directed to the same page, the form is re-initialized. In this case, you simply can NOT set the value of file for security reason.

From example, How to set a value to a file input in HTML?, you don't want this happen

<form name="foo" method="post" enctype="multipart/form-data">
    <input type="file" value="c:\passwords.txt">
</form>
<script>document.foo.submit();</script>


回答4:

Add a label tag along with the input file element. Set the 'for' attribute of the label to the id of the input file element.

Then when you click on the label the input file element will 'click' and the file dialog will open.

Then simply style the label however you like. Have tried on various IE versions.