Issue with jQuery / iframe File Uploading Solution

2019-08-01 08:06发布

问题:

I recently implemented a jQuery / iframe solution to file uploading and have run into a rather annoying issue (only in IE of course).

Upon clicking my upload button and selecting a file to upload, I automatically submit the form that contains the file to my iframe. However - I am required to click anywhere on the page in order for the submit to process and fire the action in my Controller.

I believe it is an issue with the iframe gaining focus, which seems to be stopping the 'change' function from finishing execution, but I am not entirely sure. Perhaps some type of onload function is required for the iframe to kick the focus back to the original page to continue execution?

Code:

Form & File Upload:

<form id="attachForm" action="<%= Url.Action("TestUpload","Images") %>" 
      method="post"  enctype="multipart/form-data" target='upload_target' >
        <input id='actualupload' type='file' multiple="" name='file' />
</form>
<iframe id='upload_target' name='upload_target' src='' 
        style="width:0; height: 0; border: 0;" frameborder="0"></iframe>

jQuery to Submit Form:

$("#actualupload").live('change',function()
{
    $("#attachForm").submit();
    alert("Fired!"); //This only occurs after clicking on the screen after the 
                     //file selection.
});

回答1:

It seems that .live() causes this strange behavior. If you use i.e.

$(function() {
    $("#actualupload").change( function()
    {
        $("#attachForm").submit();
        alert("Fired!"); //This only occurs after clicking on the screen after the 
                         //file selection.
    });
});

it works in IE too.