方式一:更適合H5頁面,兼容ie10+,圖片base64顯示,主要功能點是FileReader和readAsDataURLjavascript
簡潔代碼以下:html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>files-h5</title> </head> <body> <input type="file" id="file" onchange="showPreview(this, 'portrait')" /> <img src="" id="portrait" style="width: 200px; height: 200px; display: block;" /> <script> function showPreview(source, imgId) { var file = source.files[0]; if(window.FileReader) { var fr = new FileReader(); fr.onloadend = function(e) { document.getElementById(imgId).src = e.target.result; } fr.readAsDataURL(file); } } </script> </body> </html>
方式二:更適合PC端,兼容ie7+,主要功能點是window.URL.createObjectURLjava
簡潔代碼以下:this
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>files-pc</title> </head> <body> <input type="file" id="file" onchange="showPreview(this.id,'portrait')" /> <img src="" id="portrait" style="width: 200px; height: 200px; display: block;" /> <script type="text/javascript"> /* 圖片預覽 */ function showPreview(fileId, imgId) { var file = document.getElementById(fileId); var ua = navigator.userAgent.toLowerCase(); var url = ''; if(/msie/.test(ua)) { url = file.value; } else { url = window.URL.createObjectURL(file.files[0]); } document.getElementById(imgId).src = url; } </script> </body> </html>