通过javascript提交表单时,IE中的访问被拒绝错误

Kri*_*ish 7 javascript asp.net-mvc jquery file-upload

@using (Html.BeginForm("Upload", "MyProfile", FormMethod.Post, new
{
    @encType = "multipart/form-data",
    id = "ImgForm",
    name = "ImgForm",
    target = "UploadTarget"
}))
{   
    <input type="file" name="FileUpload" class="filestyle-notext fileupload">                
}

<iframe id="UploadTarget" name="UploadTarget" style="position: absolute; left: -999em; top: -999em;"></iframe>
Run Code Online (Sandbox Code Playgroud)

并通过javascript/jquery,我正在进行文件输入更改的表单提交.

$('.myprofile .fileupload').change(function () {       
    $('#ImgForm').submit();
});
Run Code Online (Sandbox Code Playgroud)

它抛出一个错误:访问被拒绝,它只发生在IE(我正在使用ie8)并在firefox,chrome中正常工作.

在论坛中阅读后,我发现由于安全原因,在IE中通过javasript提交表单存在问题,但有没有解决方法?而且我不明白为什么只有IE才会在所有浏览器支持它的时候做到这一点.IE比所有浏览器更安全吗?;)请提出您的建议.

Dar*_*rov 10

IE8不支持.submit()在.change()此文件输入的事件中调用包含文件输入的表单的事件.这是出于安全原因.您试图在没有用户明确允许的情况下向服务器提交文件.一种可能的解决方法是.submit()从您放置的某个按钮的.click()事件中调用表单:

$('.uploadButton').click(function () {       
    $('#ImgForm').submit();
});
Run Code Online (Sandbox Code Playgroud)

现在,当用户点击某个上传按钮时,表单将会提交.

值得一提的是,这只是IE8的问题.更高版本和其他浏览器没有此限制.

您也可以考虑使用基于Flash的上传控件(如Uploadify或BlueImp File上载)以跨浏览器的方式将文件上传到服务器.