图片上传在线预览是一个非常实用的功能,它可以告诉我们刚刚上传的图片是否是我们想要上传的图片,这对提升用户体验是非常有必要的。而且绝大多数的互联网应用只要有图片上传功能,都能够实时预览上传的图片。
单独的form表单上传图片是没法实时预览的,今天就来和大家分享通过jquery来实现图片上传后的在线预览功能。
通过form无表单无论上传图片还是上传其他的文件,上传的文件都会被临时存储起来,然后通过提交按钮提交给后台完成其他的操作。明白了这点,上传图片在线预览功能也就变得非常简单了:我们只需要拿到上传图片的临时存储路径,然后放到img标签里就可以显示图片了。
效果图:

下面直接上代码:
<!DOCTYPE html>
<html>
<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.com/jquery/3.3.1/jquery.js"></script>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<div>
<label for="touxiang" >图片上传:</label>
<input type="file" id="image" name="image" />
<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 ;
}
$('#image').change(function() {
var eImg=$('#imag');
eImg.attr('src', getObjectURL($(this)[0].files[0]));
$(this).after(eImg);
});
</script>
</html>window.URL.createObjectURL方法 创建一个新的对象URL,该对象URL可以代表某一个指定的File对象或Blob对象. 语法: objectURL = window.URL.createObjectURL(blob); blob参数是一个File对象或者Blob对象. objectURL是生成的对象URL.通过这个URL,可以获取到所指定文件的完整内容.
