Home  >  Article  >  Web Front-end  >  js动态在form上插入enctype=multipart/form-data的问题_表单特效

js动态在form上插入enctype=multipart/form-data的问题_表单特效

WBOY
WBOYOriginal
2016-05-16 17:53:061407browse

我们都知道要让form能提交文件,需要在form上指定enctype=multipart/form-data的attribute,这样才能上传文件,关于enctype的文章很多,就不再做解释。

问题是因为使用了MVC的Html.BeginForm()来输出表单代码,默认是没有加入enctype的,

复制代码 代码如下:

@using (Html.BeginForm()) {
}

在PartialView中有一个用来上传文件,又不想为了这个PartialView去修改父页面的Html.BeginForm(),我的做法是在PartialView中用脚本来为form加入enctype:

复制代码 代码如下:

$(function(){
$('#file').parents('form').attr('enctype', 'multipart/form-data');
});

最近的主流浏览器都测试通过没问题,唯独IE的几个旧版本出问题,试了手工在Html.BeginForm()中加入enctype是可以解决问题的,说明问题出在以上的脚本。多方查找终于发现出题出现在于IE6,7,8不支持直接attr('enctype', 'multipart/form-data'),而是设置dom属性encoding='multipart/form-data',最终的脚本代码修改为:

复制代码 代码如下:

$(function () {
$('#file').parents('form').attr('enctype', 'multipart/form-data').get(0).encoding = 'multipart/form-data';
});
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn