1 DOM结构
<form method="post" action="/CloudMarketing/limitPM/uploadFile" target="uploadFrame" id="upload" enctype="multipart/form-data">
<input name="file" accept="xls,xlsx,jpg,jpeg,pdf" value="" id="fileLocalFile" type="file">
<!-- 隐藏我们的上传文件控件 -->
<button type="button" class="yi-btn bor-primary" id="uploadBtn">上传</button>
</form>
<!-- 隐藏的iframe -->
<iframe id="uploadFrame" name="uploadFrame" width="0" height="0" border="0" style="opacity:0"></iframe>
2 JS部分
//上传文件
//监听frame的 onload方法
let oFrm = document.getElementById("uploadFrame");
oFrm.onload = oFrm.onreadystatechange = function () {
if (this.readyState && this.readyState != "complete") return;
//获取iframe里面的内容
let responseText = document.getElementById("uploadFrame").contentWindow.document.getElementsByTagName("BODY")[0].innerText;
//上传完成后的处理
if (responseText != "") {
let responseData = JSON.parse(responseText);
// alert(JSON.parse(responseText));
$('.update-file .selected-option').show();
$('.update-file .selected-option ul').html('<li><span class="name" data-id="' + responseData.RetValue.filePath + '">' + responseData.RetValue.fileName + '</span><span class="close-wrap"><i class="icon icon-close"></i></span></li>');
}
}
//监听文件路径变化
$("#fileLocalFile").change(function () {
let filePath = $("#fileLocalFile").val();
if (filePath != "") {
let extionType = filePath.substr(filePath.lastIndexOf(".") + 1);
if (extionType != "xls" && extionType != 'xlsx' && extionType != 'jpg' && extionType != 'jpeg' && extionType != 'pdf') {
alert("请上传jpg、pdf、excle等格式,大小1.5M以内的文件");
$("input[name=fileLocalFile]").val("");
return;
} else {
if ($('.update-file .selected-option ul').html() == '') {
let index = filePath.lastIndexOf("\\"),
fileName = filePath.substring(index + 1, filePath.length);
$('#upload')[0].submit();
$("input[name=fileLocalFile]").val("");
} else {
//确认弹层
$('.yi-mask').show();
$('#confirmD').show();
}
}
}
});
$('#confirmD .btnok').click(function () {
$('#confirmD').hide();
$('.yi-mask').hide();
let filePath = $("#fileLocalFile").val();
let index = filePath.lastIndexOf("\\"),
fileName = filePath.substring(index + 1, filePath.length);
$('#upload')[0].submit();
$("input[name=fileLocalFile]").val("");
});
//弹层关闭
$('#confirmD .close,#confirmD .btnok').click(function () {
$('.yi-mask').hide();
$(this).parents('.yi-modal').hide();
$("input[name=fileLocalFile]").val("");
})
3 CSS部分
#upload {
position: relative;
float: left;
}
#fileLocalFile {
opacity: 0;
filter: alpha(opacity=0);
position: absolute;
left: 0;
top: 0;
width: 70px;
height: 30px;
z-index: 1;
cursor: pointer;
}
总结:
a>
不要用其他事件来绑定file的点击事件,会造成ie8拒绝访问;
如:
$("#uploadBtn").click(function() {
$("#fileLocalFile").trigger("click");
});
b>
接口要返回字符串类型的数据,ie8接收不到json类型