<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片上传预览</title>
<script src="js/jquery.min.js"></script>
<style>
#img{width:100px;height:100px;border:1px solid #000000;}
</style>
</head>
<body>
<img src="" alt="" id="img">
<input id="uploadImage" type="file" />
<script>
$("#uploadImage").on("change", function(){
// Get a reference to the fileList 获取文件列表的引用
var files = !!this.files ? this.files : [];
// If no files were selected, or no FileReader support, return如果没有选择任何文件,或者没有FileReader支持
if (!files.length || !window.FileReader) return;
// Only proceed if the selected file is an image
if (/^image/.test( files[0].type)){
// Create a new instance of the FileReader
var reader = new FileReader();
// Read the local file as a DataURL
reader.readAsDataURL(files[0]);
// When loaded, set image data as background of div
reader.onloadend = function(){
$("#uploadPreview").css("background-image", "url("+this.result+")");
$("#img").attr("src", this.result);
}
}
});
</script>
</body>
</html>
效果图显示: