码迷,mamicode.com
首页 > Web开发 > 详细

通过createObjectURL实现图片预览

时间:2017-09-13 18:25:53      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:rip   ref   创建   trash   缓存   width   image   his   htm   

实现原理:通过createObjectURL 创建一个临时指向某地址的二进制对象。

过程:点击触发隐藏的 input   file  的点击事件,使用createObjectURL读取 file,创建一个Jquery 图片对象,url等于二进制对象。

 

 

前端代码:

 

js:  
        $(function () {
             $(‘[type=file]‘).change(function (e) {
                var file = e.target.files[0]
                preview(file, this);
            })
        });

    

   //添加图片触发隐藏的  file input
            function upLoadImage(obj) {
                return $(obj).next().click();
            }



            //预览文件图片
            function preview(file, obj) {
                //浏览器缓存一张图片
                var img = new Image(), url = img.src = URL.createObjectURL(file);
                var $img = $(img);
                img.onload = function () {
                    URL.revokeObjectURL(url)

                    var $parentBox = $(obj).parent().find(".imgBox");
                    alert(0);
                    $parentBox.html("");

                    $parentBox.css("width", "64");
                    $parentBox.css("height", "64");
                    $parentBox.append($img)
                    //$(‘#preview‘).empty().append($img)
                }
            }

 

 

 

 

html:

   <td>
                              <div class="upload-img" style="float: left; margin-right: 25px">
                                            <a href="javascript:void(0);" onclick="upLoadImage(this)" class="upload-hotel-a">
                                                <div class="imgBox">
                                                    <img src="../../images/upload.png">
                                                </div>
                                            </a>
                                            <input type="file" style="display: none" />
                                            <br />
                                            <a onclick="deleteimg(this)" class="button icon trash DeleteTd">删除</a>
                                            <input type="hidden" value="">
                                </div>
            </td>

 

通过createObjectURL实现图片预览

标签:rip   ref   创建   trash   缓存   width   image   his   htm   

原文地址:http://www.cnblogs.com/j2ee-web-01/p/7516323.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!