<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>图片上传</title> </head> <body> <!-- 要将父布局的position设置为relative,父布局将无法包裹input --> <div style="position: relative;"> <!--设置input的position为absolute,使其不按文档流排版,并设置其包裹整个布局 --> <!-- 设置opactity为0,使input变透明 --> <!-- 只接受jpg,gif和png格式 --> <input id="upload-input" style="position: absolute; top: 0; bottom: 0; left: 0;right: 0; opacity: 0;" type="file" accept="image/gif, image/jpg, image/png" onchange="showImg(this)" multiple /> <!-- 自定义按钮效果 --> <div style="text-align: top"> <span style="font-size: 12px;">上传文件:</span> <img id="upload" src="./upload.png" style=" 40px; height: 40px; vertical-align: middle;" /> </div> </div> <div id="imgContainer" style="margin-top: 10px;"></div> </body> <script type="text/javascript"> function showImg(obj) { var files = obj.files // document.getElementById("imgContainer").innerHTML = getImgsByUrl(files) getImgsByFileReader(document.getElementById("imgContainer"), files) } // 使用window.URL.createObjectURL(file)读取file实例并显示图片 function getImgsByUrl(files) { var elements = '' for (var i = 0; i < files.length; i++) { var url = window.URL.createObjectURL(files[i]) elements += "<img src='"+ url + "' style=' 40px; height: 40px; vertical-align: middle; margin-right: 5px;' />" } return elements } // 使用FileReader读取file实例并显示图片 function getImgsByFileReader(el, files) { for (var i = 0; i < files.length; i++) { let img = document.createElement('img') img.setAttribute('style', ' 40px; height: 40px; vertical-align: middle; margin-right: 5px;') el.appendChild(img) var reader = new FileReader() reader.onload = function(e) { img.src = e.target.result } reader.readAsDataURL(files[i]) } } </script> </html>