1 <!DOCTYPE html> 2 <html> 3 4 <head> 5 <meta charset="utf-8" /> 6 <title>图片上传预览</title> 7 <style> 8 .check_box{ 9 position: relative;10 width: 100px;11 height: 100px;12 margin: 20px;13 display: flex;14 flex-direction: row;15 align-items: center;16 }17 #img_preview1{18 display: block;19 width: 100px;20 height: auto;21 }22 input#zx_img1 {23 position: absolute;24 top: 0;25 left: 0;26 width: 100px;27 height: 100px;28 opacity: 0;29 z-index: 9;30 }31 32 </style>33 </head>34 35 <body>36 37 <div class="check_box">38 <img id="img_preview1" src="./images/add.png" alt="上传图片">39 <input type="file" name="file" id="zx_img1" style="padding: 0px;" accept="image/jpeg, image/jpg, image/png, image/gif "40 placeholder=" 上传文件">41 </div>42 <p>43 图片大小支持50kb以内,支持拓展名:jpg,png,gif44 </p>45 46 <!--引入jQuery插件 -->47 <script src="https://cdn.bootcss.com/jquery/3.3.0/jquery.min.js"></script>48 <script>49 $("#zx_img1").change(function (e) {50 var file = e.target.files || e.dataTransfer.files;51 if (file) {52 53 if (file[0] && (file[0].size / 1024).toFixed(0) > 50) {54 console.log(‘你选择的文件太大,文件大小为:‘ + (file[0].size / 1024).toFixed(0) + "kb");55 // return false56 }57 var reader = new FileReader();58 reader.onload = function () {59 console.log(this.result);60 $("#img_preview1").attr("src", this.result);61 }62 reader.readAsDataURL(file[0]);63 }64 });65 </script>66 </body>67 68 </html>