HTML5实现图片上传即时预览:基于window.URL.createObjectURL
作者:闭包旅人时间:2026-10-23 11:38:36浏览:496
本文介绍如何利用HTML5的window.URL.createObjectURL方法实现图片上传后的即时显示效果。通过File对象生成临时对象URL,无需服务器交互即可在客户端预览图片。文章提供了完整的HTML表单结构、jQuery事件监听代码及兼容性处理方案,帮助开发者快速掌握前端图片预览的核心技术。
前言
前言
图片上传即时显示效果
在HTML5实训项目中,我们实现了一个图片上传后即时显示的功能,效果如图所示。

正文
正文
HTML代码
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>
JavaScript脚本代码
JavaScript脚本代码
<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方法详解
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.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" 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>
参考
参考:链接
结语
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。
作者最新文章
什么时候该用JS构造器:与工厂模式、字面量的选择对比
2026-11-05 16:18:22
推荐几款轻量级JS照片墙开源库及对比
2026-11-05 15:56:19
JavaScript递归写法有哪些常见陷阱及避免方法
2026-11-05 14:53:38
JS数组浅拷贝与深拷贝怎么选?场景与方法总结
2026-11-05 14:41:02
p5.js 中 setup() 和 draw() 函数的执行机制详解
2026-11-05 12:32:38
