1:通过windowurl.createObjectURL 将选择的图片 展示在前端页面
<div><input type="file" onchange="onc(this)"></div>
<img src="" id="image">
<script type="text/javascript">
function onc(obj){ //浏览本地图片 或者视频
var fileobj=$(obj)[0];
var windowurl=window.URL||window.webkitURL;
var dataurl="";
//头像
var img=$(obj).next().children("img");
if(fileobj&&fileobj.files&&fileobj.files[0]){
dataurl=windowurl.createObjectURL(fileobj.files[0]);
$("#image").attr("src",dataurl);
}
}
</script>
2:HTML5 FileReader() 我们能够在上传前预览图片
<div id="wrapper" style="margin-top: 20px;"><input id="fileUpload" type="file"/>
<div id="image-holder"></div>
<img src="" id="thumb-image">
</div>
<script>
$(document).ready(function() {
$("#fileUpload").on('change', function () {
if (typeof (FileReader) != "undefined") {
var image_holder = $("#image-holder");
image_holder.empty();
var reader = new FileReader();
reader.onload = function (e) {
$("#thumb-image").attr("src",e.target.result);
/* $("<img />", {
"src": e.target.result,
"class": "thumb-image"
}).appendTo(image_holder); */
}
image_holder.show();
reader.readAsDataURL($(this)[0].files[0]);
} else {
alert("This browser does not support FileReader.");
}
});
});
</script>
3:HTML5 FileReader() 多图片上传实现预览
<div id="wrapper" style="margin-top: 20px;"><input id="fileUpload" multiple="multiple" type="file"/>
<div id="imagemore"></div>
</div>
<script>
$(document).ready(function() {
$("#fileUpload").on('change', function() {
//获取用户选择文件列表 此处限制为图片
var countFiles = $(this)[0].files.length;
var imgPath = $(this)[0].value;
var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
if (typeof(FileReader) != "undefined") {
for (var i = 0; i < countFiles; i++) {
var reader = new FileReader();
reader.onload = function(e) {
var table ='<img src='+e.target.result+' style="width:25%;height:25%"/>';
$("#imagemore").append(table);
}
reader.readAsDataURL($(this)[0].files[i]);
}
} else {
layer.msg("此浏览器不支持文件读取器,请更换浏览器尝试上传图片",{icon:2});
}
} else {
layer.msg("请选择上传图片",{icon:2});
}
});
});
</script>