HTML5---傳送檔案【圖片】
<!DOCTYPE html> <html lang="en">
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> *{ margin: 0; padding: 0; } .file-box{ margin: 20px auto; border: 1px solid #ccc; width: 600px; padding: 12px 12px 12px 18px; } .file-box .load{ position: relative; } .file-box .load #file{ width: 32px; height: 32px; opacity: 0; position: absolute; left: 0; top: 0; cursor: pointer; } .file-box .load img{ width: 32px; height: 32px; } .file-box .load button{ float: right; width: 60px; height: 32px; line-height: 32px; text-align: center; color: #fff; background: mediumpurple; outline: none; border: none; border-radius: 4px; cursor: pointer; } .load-show{ margin-top: 10px; border: 1px solid; width: 100%; height: auto; } .load-show img{ width: 200px; height: 200px; padding: 20px; } </style> </head>
<body> <div class="file-box"> <div class="load"> <input type="file" id="file"/> <img src="img/load.png" /> <button type="button">傳送</button> </div> <div class="load-show">
</div> </div> <script> //獲取檔案url function createObjectURL(blob) { if(window.URL) { return window.URL.createObjectURL(blob); } else if(window.webkitURL) { return window.webkitURL.createObjectURL(blob); } else { return null; } }
var show = document.querySelector(".load-show"); //顯示圖片box var file = document.querySelector("#file"); //file物件 var domFragment = document.createDocumentFragment(); //文件流優化多次改動dom
//觸發選中檔案事件 file.onchange = function(e) { // show.innerHTML = ""; //清空上一次顯示圖片效果,只能單張圖設定 e = e || event; var file = this.files; //獲取選中的檔案物件
for(var i = 0, len = file.length; i < len; i++) { var imgTag = document.createElement("img"); var fileName = file[i].name; //獲取當前檔案的檔名 var url = createObjectURL(file[i]); //獲取當前檔案物件的URL
//忽略大小寫 var jpg = (fileName.indexOf(".jpg") > -1) || (fileName.toLowerCase().indexOf(".jpg") > -1); var png = (fileName.indexOf(".png") > -1) || (fileName.toLowerCase().indexOf(".png") > -1); var jpeg = (fileName.indexOf(".jpeg") > -1) || (fileName.toLowerCase().indexOf(".jpeg") > -1);
//判斷檔案是否是圖片型別 if(jpg || png || jpeg) { imgTag.src = url; domFragment.appendChild(imgTag); } else { alert("請選擇圖片型別檔案!"); } }
//最佳顯示 show.appendChild(domFragment);
} </script> </body>
</html>