标签:
在文件上传之前,我们总想预览一下文件内容,或图片样子,html5 中FileReader正好提供了2种方法,可以在不上传文件的情况下,预览文件内容。
图片预览:readAsDataURL(file);
文件预览:readAsText();(必须保证文件编码格式与代码编码格式相同,预览中文才不会乱码)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>HTML5练习</title> <style type="text/css"> </style> </head> <body> <input type = file id = ‘file‘/> <input type = button onclick = ‘readImg()‘ value = ‘读取图像‘/> <input type = button onclick = ‘readFile()‘ value = ‘读取文件‘/> <div id = ‘result‘></div> <script language = ‘javascript‘> function showFileName(){ var files = document.getElementById(‘file‘).files; var file; for(var i = 0, len = files.length; i < len; i++){ file = files[i]; console.log(file.name); } } function readImg(){ var file = document.getElementById(‘file‘).files[0]; if(!/image\/\w+/.test(file.type)){ alert("请确保文件为图像类型!"); return false; } var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function(e){ var result = document.getElementById(‘result‘); result.innerHTML = "<img src = ‘"+this.result+"‘ alt = ‘‘/>"; }; } function readFile(){ var file = document.getElementById(‘file‘).files[0]; var reader = new FileReader(); reader.readAsText(file); reader.onload = function(f){ var result = document.getElementById(‘result‘); result.innerHTML = this.result; } } </script> </body> </html>
标签:
原文地址:http://www.cnblogs.com/codelovers/p/4415590.html