<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>html5 图片上传预览</title>
<style>
#preview {
width: 300px;
height: 300px;
overflow: hidden;
}
#preview img {
width: %;
height: %;
}
</style>
<script src="../static/js/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
//方法一
function preview1(file) {
var img = new Image(), url = img.src = URL.createObjectURL(file);
var $img = $(img);
img.onload = function() {
URL.revokeObjectURL(url);
$('#preview').empty().append($img)
}
}
//方法二
function preview2(file) {
var reader = new FileReader();
reader.onload = function(e) {
var $img = $('<img>').attr("src", e.target.result);
$('#preview').empty().append($img)
};
reader.readAsDataURL(file)
}
$(function() {
$('[type=file]').change(function(e) {
var file = e.target.files[];
preview1(file);
//preview2(file)
})
})
</script>
</head>
<body>
<form enctype="multipart/form-data" action="" method="post">
<input type="file" name="imageUpload"/>
<div id="preview" style="width: 300px;height:300px;border:1px solid gray;"></div>
</form>
</body>
</html>