<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta charset="utf-8" /> <meta name="referrer" content="never"> <title>直接预览本地图片,支持 IE8</title> </head> <body> <h2>JavaScript 直接预览本地图片,支持 IE8</h2> <input type="file" id="fileInput" /> <div id="previewContainer" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale);width:64px; height:64px;margin-top:10px;"> <img id="previewImage" src="/favicon.ico" style="width:100%; height:100%;" /> </div> </body> </html>
function preImg(fileInput, containerId, imageId) { var allowedExts = [".jpg", ".jpeg", ".gif", ".png", ".bmp"]; var fileExt = fileInput.value.substring(fileInput.value.lastIndexOf('.'), fileInput.value.length).toLowerCase(); if (allowedExts.indexOf(fileExt) == -1) { fileInput.value = ""; alert("只能上传 jpg gif png bmp 格式图片"); } else { var container = document.getElementById(containerId); var image = document.getElementById(imageId); if (container.filters) { image.style.display = "none"; fileInput.select(); container.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = document.selection.createRange().text; } else { image.src = window.URL.createObjectURL(fileInput.files.item(0)); } } } var fileInput = document.getElementById('fileInput'); fileInput.onchange = function () { preImg(fileInput, 'previewContainer', 'previewImage'); }