凌的博客

您现在的位置是: 首页 > 前端学习 > Js > 

Js

js本地预览图片

2016-09-14 Js 850
function getFileUrl(obj){ var Setting = { ImgType: [\"gif\", \"jpeg\", \"jpg\", \"bmp\", \"png\"] } var _this = obj; var url = null; if (_this.value) { if (!RegExp(\"\\.(\" + Setting.ImgType.join(\"|\")
function getFileUrl(obj){
	var Setting = {
			ImgType: ["gif", "jpeg", "jpg", "bmp", "png"]
		}
	var _this = obj;
	var url = null;
	if (_this.value) {
		if (!RegExp("\.(" + Setting.ImgType.join("|") + ")$", "i").test(_this.value.toLowerCase())) {
			alert("选择文件错误,图片类型必须是(gif,jpeg,jpg,bmp,png)中的一种");
			_this.value = "";
			return false;
		}
		if (navigator.userAgent.indexOf("MSIE") > -1) {
			try {
				_this.select();
				url = document.selection.createRange().text;
				//url = getObjectURL(_this.files[0]);
			} catch (e) {
				alert(e);
			}
		} else {
			url = getObjectURL(_this.files[0]);
		}
	}
	//console.log(url);
	$("#imgshow").html('<img src="'+url+'" />');
	
	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;
	}	
}
//<input type="file" onChange="getFileUrl(this)" name="image" />
//<div id="imgshow"></div>

文章评论

0条评论