<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script> var __userAgent = window.navigator.userAgent; isIE = /msie\s+(.*?)\;/i.test(__userAgent); isFF = !isIE&&/rv\:(.*?)\)\s+gecko\//i.test(__userAgent); function imageChange() { var file = document.getElementById('__file__'); var _fileurl = file.value; if (typeof FileReader != 'undefined' && !!FileReader) { //html5 var reader = new FileReader(); reader.readAsDataURL(file.files[0]); reader.onload = preview; reader.onerror = function(evt){console.log("load fail:[error="+evt.target.error.code+"]")}; } else { if (isIE) { var _version = getInternetExplorerVersion(); if (_version >= 7.0) { file.select(); try{ _fileurl = document.selection.createRange().text; if (!_fileurl || _fileurl == '') { _fileurl = file.value; } } finally { document.selection.empty(); } } } if (isFF){ //不支持html5的低版本ff _fileurl = file.files[0].getAsDataURL(); } preview(_fileurl); } } function preview(fileurl){ var img = document.getElementById('__image__'); if (typeof FileReader != 'undefined' && !!FileReader) { fileurl = fileurl.target.result; } if (!isImage(fileurl)){ alert('请选择正确的图片文件!'); return; } img.src = fileurl; } function isImage(url) { return /^data:image|\.(?:jpg|png|jpeg|gif|bmp)\s*$/i.test(url); } function getInternetExplorerVersion() { var rv = -1; // Return value assumes failure. if (navigator.appName == 'Microsoft Internet Explorer') { var ua = navigator.userAgent; var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})"); if (re.exec(ua) != null) rv = parseFloat( RegExp.$1 ); } return rv; }; </script> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> </head> <body> <input type="file" id="__file__" onchange="imageChange()" onpropertychange="imageChange()"/> <div><img id="__image__" src=""></div> </body> </html>
不支持safari和opera。
在chrome中直接打开html文件不能加载图片,会报NOT_READABLE_ERR,必须通过服务器来访问。