js实现图片上传即时显示效果
网络编程 2021-07-04 15:01www.168986.cn编程入门
这篇文章主要为大家详细介绍了js实现图片上传即时显示效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
前言
h5实训时实现的一个图片上传即时显示的效果,如下图所示
正文
Html代码
<form action="" method="POST" role="form"> <div class="form-group"> <label for="touxiang" >头像上传:</label> <input type="file" id="headPhoto" name="headPhoto" /> <div ><img id="imag" src="img/up.png" alt="" style="height:5rem;width: 5rem;"></div> </div> </form>
js脚本代码
<script>
/显示上传的图片/
function getObjectURL(file) {
var url = null ;
if (window.createObjectURL!=undefined) {
url = window.createObjectURL(file) ;
} else if (window.URL!=undefined) {
url = window.URL.createObjectURL(file) ;
} else if (window.webkitURL!=undefined) {
url = window.webkitURL.createObjectURL(file) ;
}
return url ;
}
$('#headPhoto').change(function() {
var eImg=$('#imag');
eImg.attr('src', getObjectURL($(this)[0].files[0]));
$(this).after(eImg);
});
</script>
window.URL.createObjectURL方法
创建一个新的对象URL,该对象URL可以代表某一个指定的File对象或Blob对象.
语法:
objectURL = window.URL.createObjectURL(blob);
blob参数是一个File对象或者Blob对象.
objectURL是生成的对象URL.通过这个URL,可以获取到所指定文件的完整内容.
完整代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>图片上传</title>
<script src="https://cdn.bootcss./jquery/3.3.1/jquery.js"></script>
<link href= rel="stylesheet">
<script src="https://maxcdn.bootstrapcdn./bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<form action="" method="POST" role="form">
<div class="form-group">
<label for="touxiang" >头像上传:</label>
<input type="file" id="headPhoto" name="headPhoto" />
<div ><img id="imag" src="img/up.png" alt="" style="height:5rem;width: 5rem;"></div>
</div>
</form>
</body>
<script>
/显示上传的图片/
function getObjectURL(file) {
var url = null ;
if (window.createObjectURL!=undefined) {
url = window.createObjectURL(file) ;
} else if (window.URL!=undefined) {
url = window.URL.createObjectURL(file) ;
} else if (window.webkitURL!=undefined) {
url = window.webkitURL.createObjectURL(file) ;
}
return url ;
}
$('#headPhoto').change(function() {
var eImg=$('#imag');
eImg.attr('src', getObjectURL($(this)[0].files[0]));
$(this).after(eImg);
});
</script>
</html>
参考
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持狼蚁SEO。
上一篇:vue自动化路由的实现代码 下一篇:vue实现select下拉显示隐藏功能