1. 程式人生 > >圖片上傳前預覽演示

圖片上傳前預覽演示

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>圖片上傳前預覽演示</title>
<script src="http://cdn.bootcss.com/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery.fn.extend({
    preview: function (opts) {
        var _self = this,
            _this = $(this);
        opts = jQuery.extend({
            img: "img",
            imgType: ["jpeg", "jpg", "gif", "bmp", "png"]
        }, opts || {});
        _self.getObjectURL = function (file) {
            var url = null;
            if (window.createObjectURL != undefined) {
                url = window.createObjectURL(file)
            } else if (window.URL != undefined) {
                url = window.URL.createObjectURL(file)
            } else if (window.webkitURL != undefined) {
                url = window.webkitURL.createObjectURL(file)
            }
            return url
        };
        _this.change(function () {
            if (this.value) {
                if (!RegExp("\.(" + opts.imgType.join("|") + ")$", "i").test(this.value.toLowerCase())) {
                    alert("請選擇以下型別圖片:" + opts.imgType.join(",") );
                    this.value = "";
                    return false
                }
                
                $("#" + opts.img).attr('src', _self.getObjectURL(this.files[0]));
            }
        })
    }
});
</script>
<script>
$(function () {
$("#up").preview({ img: "img",width:"100px"});
});
</script>
</head>
<body>
<div style="width:500px;margin:0px auto;"><h2>圖片上傳前預覽演示</h2>

<div><img id="img" width="200px"  /></div>
<input type="file" id="up" />
</div>

</body>
</html>