通过createObjectURL实现图片预览

时间:2024-09-27 16:08:02

实现原理:通过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)
                }
            }

//删除

function deleteimg(obj) {
                var objectBox = $(obj).parent().find(".imgBox");
                var file = $(obj).parent().find(".fileData");
                $(file).val('');
                objectBox.html("<img src='../../images/upload.png'>");
            }

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>