jquery實現圖片上傳前本地預覽

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="js/jquery1.8.3-min.js"></script>
</head>
<body>
<div style="width:500px;margin:0px auto;"><h2>圖片上傳預覽演示</h2>
<div><img id="ImgPr" width="120" height="120" /></div>
<input type="file" id="up" />
</div>
<script>
/*
*參數說明: Img:圖片ID;Width:預覽寬度;Height:預覽高度;ImgType:支持文件類型;Callback:選擇文件顯示圖片後回調方法;
*使用方法:
<div>
<img id="ImgPr" width="120" height="120" /></div>
<input type="file" id="up" />
把須要進行預覽的IMG標籤外 套一個DIV 而後給上傳控件ID給予uploadPreview事件
$("#up").uploadPreview({ Img: "ImgPr", Width: 120, Height: 120, ImgType: ["gif", "jpeg", "jpg", "bmp", "png"], Callback: function () { }});
*/
jQuery.fn.extend({
uploadPreview: function (opts) {
var _self = this,
_this = $(this);
opts = jQuery.extend({
Img: "ImgPr",
Width: 100,
Height: 100,
ImgType: ["gif", "jpeg", "jpg", "bmp", "png"],
Callback: function () {}
}, 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
}
if ($.browser.msie) {
try {
$("#" + opts.Img).attr('src', _self.getObjectURL(this.files[0]))
} catch (e) {
var src = "";
var obj = $("#" + opts.Img);
var div = obj.parent("div")[0];
_self.select();
if (top != self) {
window.parent.document.body.focus()
} else {
_self.blur()
}
src = document.selection.createRange().text;
document.selection.empty();
obj.hide();
obj.parent("div").css({
'filter': 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)',
'width': opts.Width + 'px',
'height': opts.Height + 'px'
});
div.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = src
}
} else {
$("#" + opts.Img).attr('src', _self.getObjectURL(this.files[0]))
}
opts.Callback()
}
})
}
});

$(function () {
$("#up").uploadPreview({ Img: "ImgPr", Width: 120, Height: 120 });
});
</script>
</body>
</html>
相關文章
相關標籤/搜索