HTML5File et FileReaderinterface
<!DOCTYPE html><html><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>HTML5文件拖拽预览Demo</title> <style type="text/css"> h1{ padding:0px; margin:0px; } p#show{ border: 1px solid #ccc; width: 400px; height: 300px; display: -moz-box; display: -webkit-box; -moz-box-align: center; -webkit-box-align: center; -moz-box-pack: center; -webkit-box-pack: center; resize:both; overflow:auto; } p[id^=show]:hover{ border: 1px solid #333; } p#main{ width:100%; } p#successLabel { color:Red; } p#content { display:none; } </style> <script type="text/javascript"> function init() { var dest = document.getElementById("show"); dest.addEventListener("dragover", function(ev) { ev.stopPropagation(); ev.preventDefault(); }, false); dest.addEventListener("dragend", function(ev) { ev.stopPropagation(); ev.preventDefault(); }, false); dest.addEventListener("drop", function (ev) { ev.stopPropagation(); ev.preventDefault(); var file = ev.dataTransfer.files[0]; var reader = new FileReader(); if (file.type.substr(0, 5) == "image") { reader.onload = function (event) { dest.style.background = 'url(' + event.target.result + ') no-repeat center'; dest.innerHTML = ""; }; reader.readAsDataURL(file); } else if (file.type.substr(0, 4) == "text") { reader.readAsText(file); reader.onload = function (f) { dest.innerHTML = "<pre class="brush:php;toolbar:false">" + this.result + ""; dest.style.background = "white"; } } else { dest.innerHTML = "暂不支持此类文件的预览"; dest.style.background = "white"; } }, false); } //设置页面属性,不执行默认处理(拒绝被拖放) document.ondragover = function(e){e.preventDefault();}; document.ondrop = function(e){e.preventDefault();} window.onload=init;
文件预览区,仅限图片和txt文件