1 <!DOCTYPE HTML> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>html5 图片上传预览</title> 6 <style> 7 #preview { 8 300px; 9 height: 300px; 10 overflow: hidden; 11 } 12 #preview img { 13 100%; 14 height: 100%; 15 } 16 </style> 17 <script src="../static/js/jquery-1.11.2.min.js"></script> 18 <script type="text/javascript"> 19 20 21 //方法一 22 function preview1(file) { 23 var img = new Image(), url = img.src = URL.createObjectURL(file); 24 var $img = $(img); 25 img.onload = function() { 26 URL.revokeObjectURL(url); 27 $('#preview').empty().append($img) 28 } 29 } 30 31 32 //方法二 33 function preview2(file) { 34 var reader = new FileReader(); 35 reader.onload = function(e) { 36 var $img = $('<img>').attr("src", e.target.result); 37 $('#preview').empty().append($img) 38 }; 39 reader.readAsDataURL(file) 40 } 41 42 43 $(function() { 44 $('[type=file]').change(function(e) { 45 var file = e.target.files[0]; 46 preview1(file); 47 //preview2(file) 48 }) 49 }) 50 </script> 51 </head> 52 <body> 53 <form enctype="multipart/form-data" action="" method="post"> 54 <input type="file" name="imageUpload"/> 55 <div id="preview" style=" 300px;height:300px;border:1px solid gray;"></div> 56 </form> 57 </body> 58 </html>