ie javascript form submit with file input

后端 未结 8 532
-上瘾入骨i
-上瘾入骨i 2020-12-02 17:35

I have a html form, with a custom file upload field. And by that I mean that I have moved the actual file field beyond the borders of the page with css, that I have a custom

8条回答
  •  时光取名叫无心
    2020-12-02 17:54

    I was having the same problem, and I solved it by using a styled tag with a slight workaround in Firefox.

    http://jsfiddle.net/djibouti33/uP7A9/

    The Goals:

    1. allow user to upload a file by using standard html file input control
    2. hide standard html file input control and apply own styling
    3. after user selects file to upload, automatically submit the form

    The Browsers:

    • Firefox, Chrome, IE8/9, Safari
    • IE7 didn't work, but it might if you add it to the workaround detailed below.

    The Initial Solution:

    1. Hide the file input by positioning it offscreen. Important not to display:none as some browsers won't like this.
    2. Add another styled element to the page (link, button).
    3. Listen for a click on that element, then programmatically send a click to the file input to trigger the native 'file explorer'
    4. Listen for the file input's onchange event (occurs after a user chooses their file)
    5. Submit the form

    The Problem:

    1. IE: if you programmatically send a click to a file input in order to activate it (2), programmatically submitting the form (5) will throw a security error

    The Workaround Solution:

    1. Same as above
    2. Take advantage of the accessibility features built in to the label tag (clicking on a label will activate it's associated control) by styling a label tag instead of a link/button
    3. Listen for the file input's onchange event
    4. Submit the form
    5. For some reason Mozilla browsers won't activate a file input by clicking on it's label.
    6. For Mozilla, listen for the click on the label and send a click event to the file input to activate it.

    Hope this helps! Check out the jsfiddle for details on the html/js/css used to make it all work.

提交回复
热议问题