前端图片预览

 网站后台页面有一个功能,管理员上传图片的时候实现预览,这个功能想到两种实现方法:

1.每次添加图片服务端处理图片,ajax传回缩略图,在页面展示。

2.前端实现预览,只有当提交表单的时候才跟服务器交互。

前端预览的好处显而易见,减少跟服务器的请求次数。百度了下,前端完全能实现这个功能,这个功能也就转化成了前端读取本机文件。考虑到网站是给内部人员用的,不用考虑浏览器兼容的问题,实现起来就简单多了。

没什么好说的,上传图片用这个标签<input type="file">,这个元素的属性files(是个FileList对象),通过这个特性就可以读取本机的文件了。files的详细介绍可以阅读《javaScript权威指南》,或者参考这个博文:http://blog.csdn.net/oscar999/article/details/37499743

每次选择文件后,立即显示选择图片预览,就要用到input的onchang事件。本文不用file的操作方式,而是用URL.createObjectURL(),该方法会根据传入的参数创建一个指向该参数对象的URL.

效果:

 

下面是代码:

 1 <!doctype html>
 2 <html>
 3 <head>
 4 <meta charset="utf-8">
 5 <title>无标题文档</title>
 6 </head>
 7 
 8 <body>
 9     <form action="http://www.baidu.com" method="get">
10          <div class="control-group">
11                        <label class="control-label">缩略图</label>
12                        <div class="controls">
13                            <span id="imgContent">
14                               
15                           </span>
16                           <img style="50px;height:50px;margin-left: 10px;" src="img/i_addphoto.png" onclick="$('#img').click()">
17                         <div style="opacity: 0;height: 0px;">
18                             <input type="file" name="img" id="img" data-content="imgContent" multiple/>
19                         </div>
20                        </div>
21           </div>
22           <br/>
23                 <input type="submit"/>
24     </form>
25 <!--引用百度的juery库-->
26 <script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
27 <script>
28 //工具函数,可以作为尾部文件引用进来。
29     function getObjectURL(file) {
30         var url = null ; 
31         if (window.createObjectURL!=undefined) { // basic
32             url = window.createObjectURL(file) ;
33         } else if (window.URL!=undefined) { // mozilla(firefox)
34             url = window.URL.createObjectURL(file) ;
35         } else if (window.webkitURL!=undefined) { // webkit or chrome
36             url = window.webkitURL.createObjectURL(file) ;
37         }
38         return url ;
39     }
40 </script>
41 <script>
42 //从本地添加了文件后,触发onchange事件。
43     $("input[type='file']").change(function(e) {
44             $("#"+$(this).attr("data-content")).html('');
45             for (var i = 0; i < this.files.length; i++) {
46                 $("#"+$(this).attr("data-content")).append('<img style="50px;height:50px;margin-left: 10px;" src="'+getObjectURL(this.files[i])+'">');
47             }
48         });
49 </script>
50 </body>
51 </html>
原文地址:https://www.cnblogs.com/xiaochongchong/p/5420681.html