URL图片预览(createObjectURL)

1.说明

1)createObjectURL

  作用:创建url(creates  a URL for the specified object);

  语法:var url = URL.createObjectURL(object,options);

  参数说明:1)object可以包含下列类型:Blob,MSStram,IstaorageItem,MediaCapture,IRandomAccessStreamWithContentType,

       2)options若设置为true,则是oneTimeOnly attribute,doesn't need to be revoked once used,即只是用一次

2)revokeObjectURL

  作用:将对象鱼url关联(rovokes a URL from  a document and frees the object associated with that URL)

  语法:var retval = URL.revokeObjectURL(url);

 

2.例子

<!DOCTYPE HTML>
<html>
    <head>
    <meta charset="utf-8">
    <style>
        #preview {
            width: 300px;
            height: 300px;
            overflow: hidden;
        }
        #preview img {
            width: 100%;
            height: 100%;
        }
    </style>
    <script src="../js/jquery-1.9.1.min.js"></script>
</head>
<body>
<form enctype="multipart/form-data" action="" method="post">
    <input type="file" name="imageUpload"/>
    <div id="preview" style="width: 300px;height:300px;border:1px solid gray;"></div>
</form>
</body>
 <script type="text/javascript">
        $(function(){
            $('[type="file"]').change(function(e){
                var file = e.target.files[0];
                preview(file);
            });
        })
        function preview(file){
            var img = new Image();
            url = img.src=URL.createObjectURL(file);
            var $img = $(img);
            img.onload = function(e){
                URL.revokeObjectURL(url);
                $('#preview').empty().append($img);
            }
        }
    </script>
</html>

效果如下:(点击上传后立刻在页面上显示)

posted @ 2014-04-06 12:50  wishyouhappy  阅读(2997)  评论(0编辑  收藏  举报