HTML5 + JS achieve a simple image upload preview

Directly on the code

 1 <!DOCTYPE HTML>
 2 <html>
 3   <head>
 4   <meta charset="utf-8">
 5   <title>HTML5 图片上传预览</title>
 6   <style>
 7     #preview {
 8       width: 300px;
 9       height: 300px;
10       overflow: hidden;
11     }
12     IMG #preview { 
13 is        width : 100% ; 
14        height : 100% ; 
15      } 
16    </ style > 
. 17    <! - example had to use the local jQuery, the following references into line -> 
18    <-! - <Script src = "jQuery-1.7.2.min.js"> </ Script> -> 
19    <-! all versions of jQuery online references - Xiao Peng Wei - CSDN blog -> 
20    <-! HTTPS: / /blog.csdn.net/qq_40147863/article/details/83116859 -> 
21 is    < Script the src = "http://libs.baidu.com/jquery/1.7.2/jquery.min.js"></Script > 
22    < Script of the type = "text / JavaScript" > 
23      // JS + HTML5 to upload pictures preview complete examples available [test] _javascript skills _ script Home 
24-      // https://www.jb51.net/article /111651.htm 
25      // URL.createObjectURL and URL.revokeObjectURL - Poetry & distance - blog Park 
26      // https://www.cnblogs.com/liulangmao/p/4262565.html 
27      function preview1 (File) { // does not support lower versions of the browser 
28        var img =  new new Image (), url = img.src = URL.createObjectURL (File);
 29        var $ img= $(img)
30       img.onload = function() {
31         URL.revokeObjectURL(url);
32         $('#preview').empty().append($img);
33       }
34     }
35     function preview2(file) {
36       var reader = new FileReader();
37       reader.onload = function(e) {
38         var $img = $('<img>').attr("src", E.target.result);
 39          $ ( ' #preview ' ) .empty () the append ($ IMG);.
 40        }
 41 is        reader.readAsDataURL (File);
 42 is      }
 43 is       
44 is      $ ( function () {
 45        $ ( ' [type = File] ' ) .change ( function (E) {
 46 is          var File = e.target.files [ 0 ];
 47          // preview1 (File); // process the browser does not support low version 
48          Preview2 ( File); // method 2 
49        })
 50     })
51   </script>
52 </head>
53 <body>
54 <form enctype="multipart/form-data" action="" method="post">
55   <input type="file" name="imageUpload"/>
56   <div id="preview" style="border:1px solid gray;"></div>
57 </form>
58 </body>
59 </html>

 

Guess you like

Origin www.cnblogs.com/tobyhan/p/11409322.html