文件上传
js
function imgChange(fileId,event,callback){
var imgType=[".jpg",".jpeg",".png",".gif"]
var myfiles=event.currentTarget.files[0]
var name = myfiles.name;
var size = myfiles.size; //读取选中文件的大小
var type = myfiles.type;
var fileType=myfiles.type.indexOf("image")>=0?"image":"files";
const imgObj={name, size, type, fileType}
var file = document.getElementById(fileId);
if(window.FileReader){//chrome,firefox7+,opera,IE10+
oFReader = new FileReader();
oFReader.readAsDataURL(file.files[0]);
oFReader.onload = function (oFREvent) {
imgObj.src = oFREvent.target.result;
callback(imgObj)
};
}
else if (document.all) {//IE9-//IE使用滤镜,实际测试IE6设置src为物理路径发布网站通过http协议访问时还是没有办法加载图片
file.select();
file.blur();//要添加这句,要不会报拒绝访问错误(IE9或者用ie9+默认ie8-都会报错,实际的IE8-不会报错)
var reallocalpath = document.selection.createRange().text//IE下获取实际的本地文件路径
//if (window.ie6) pic.src = reallocalpath; //IE6浏览器设置img的src为本地路径可以直接显示图片
//else { //非IE6版本的IE由于安全问题直接设置img的src无法显示本地图片,但是可以通过滤镜来实现,IE10浏览器不支持滤镜,需要用FileReader来实现,所以注意判断FileReader先
imgObj.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='image',src=\"" + reallocalpath + "\")";
imgObj.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';//设置img的src为base64编码的透明图片,要不会显示红xx
callback(imgObj)
// }
}
else if (file.files) {//firefox6-
if (file.files.item(0)) {
url = file.files.item(0).getAsDataURL();
imgObj.src = url;
callback(imgObj)
}
}
}
调用
$('.upload-box input[type=file]').on('change', function( event ){
var e=window.event|| event
var id=$(this).attr("id");
var $this=$(this)
//e.currentTarget.files 是一个数组,如果支持多个文件,则需要遍历
imgChange(id,e,function(obj){
console.log(obj)
var src=obj.src;
var name=obj.name;
console.log("src",src)
$this.parent().find("span").html('<img src="'+src+'" />')
})
});
html
<div class="form-group upload required">
<label for="identity_card">身份证</label>
<a class="upload-box">
<button type="button" ><i class="layui-icon"></i>上传图片</button>
<span></span>
<input class="form-control-file" id="identity_card" name="identity_card" required type="file" accept="image/gif, image/jpeg,image/png" data-show-preview="false">
</a>
</div>
css
.upload label{
display: inline-block;
margin-right: 10px;
}
.upload-box{
position: relative;
display: inline-block;
height: 40px;
cursor: pointer;
}
.upload-box button{
height: 40px;
min-width: 100px;
border:1px solid #DDD;
background-color: transparent;
}
.upload-box button i{
margin-right: 3px;
color: #666;;
}
.upload-box input[type="file"] {
height: 40px;
opacity: .01;
filter: Alpha(opacity=1);
position: absolute;
left: 0;
top: 0;
}
.upload-box span img{
height: 100%;
width: auto;
margin-left: 5px;
}
转载于:https://www.cnblogs.com/webqiand/articles/11250297.html