这是我参与8月更文挑战的第18天,活动详情查看:8月更文挑战
ie9 10 无法识别 input type=file 的二进制对象
图片预览然后上传。但是IE9中event.target.files[0]没用,好像还没有FileReader方法。我现在该怎么做呢?
<input type="submit" value="Submit" />
准备知识
判断浏览器
if (navigator.userAgent.indexOf("MSIE 9.0")>0 || navigator.userAgent.indexOf("MSIE 10.0")>0) {
this.ie9 = true;
}
具体步骤
只有在ie9 才会显示的html, target 指向一个 iframe 的id,其他情况正常显示,正常调用
<form v-if="ie9" id='formFile' name='formFile' method="post" action='http://localhost:8080/api/common/file/file2' target='frameFile' enctype="multipart/form-data">
<input type='file' class="up-input2" id='fileUp' name='file' @change="uploadAnnex()"/>
</form>
<!--
这个iframe拿到post过来的表单数据后会开始在自身内部访问post过来的页面地址,在内部中它会刷新页面,
但是这已不重要了,因为当前的iframe已经被我display:none隐藏了!所以这样给用户看起来像是无刷新的
页面文件上传,其实只是做一个一个小小的技巧!
-->
<iframe id='frameFile' name='frameFile'></iframe>
js 的调用
getFile('#formFile input')
var inputDomStr = '#formFile';
var frame= $(inputDomStr);
//提交 from 表单
frame.submit();
//清空 input type file 的value值 防止无法重复提交同一个文件
emptyFile(inputDomStr , this.uploadAnnexIe9)
//监听 ifrom 的load 方法,来得到 接口的返回值
document.getElementById("frameFile").onload=function(){
var result=document.getElementById('frameFile').contentWindow.document.body.innerText;
alert(result)
}
周边知识点
用input file上传文件,掉用onchange方法时,多次上传同一个文件时功能失效,不会发送ajax请求
input[type=file]使用的是onchange去做,onchange监听的为input的value值,只有再内容发生改变的时候去触发,而value在上传文件的时候保存的是文件的内容,你只需要在上传成功的回调里面,将当前input的value值置空即可。event.target.value=“”;
清空input type value 值
function emptyFile(inputDomStr,backFun){
let target = $(inputDomStr);
target.val("");
var cf=target.clone();
target.after(cf);
target.remove();
$(inputDomStr).on('change',()=>{
backFun && backFun();
})
}
用input file上传文件,前端可以得到文件的信息
得到文件的大小
function getFileSize(obj){
try{
var file = obj;
file.select();
file.blur();
var path = document.selection.createRange().text;
var fso = new ActiveXObject("Scripting.FileSystemObject");
fileSize = fso.GetFile(path).size;
alert(fileSize);//弹出文件大小
}catch(e){
alert(e+"\n"+"如果错误为:Error:Automation 服务器不能创建对象;"+"\n"+"请按以下方法配置浏览器:"+"\n"+"请打开【Internet选项-安全-Internet-自定义级别-ActiveX控件和插件-对未标记为可安全执行脚本的ActiveX控件初始化并执行脚本(不安全)-点击启用-确定】");
return window.location.reload();
}
}