HTML 語法:
<input id="FileSelected" type="file" />
<input id="FileSelected" type="file" multiple="multiple" />
<input id="FileSelected" type="file" accept="image/*" />
使用 DOM 獲取選擇的檔案:
var selectedFile = document.getElementById('input').files[0];
使用 jQuery 獲取選擇的檔案:
var selectedFile = $('#input').get(0).files[0]; var selectedFile = $('#input')[0].files[0];
使用 change event 獲取選擇的檔案
<input id="input" onchange="handleFiles(this.files)" type="file" />
使用 EventListener 動態地監聽
var inputElement = document.getElementById("inputField"); inputElement.addEventListener("change", handleFiles, false); function handleFiles() { var fileList = this.files; /* now you can work with the file list */ }
範例 (Html Page)
<!DOCTYPE html> <html> <body onload="myFunction()"> <input type="file" id="myFile" multiple size="50" onchange="myFunction()"> <p id="demo"></p> <script> function myFunction(){ var x = document.getElementById("myFile"); var txt = ""; if ('files' in x) { if (x.files.length == 0) { txt = "Select one or more files."; } else { for (var i = 0; i < x.files.length; i++) { txt += "<br><strong>" + (i+1) + ". file</strong><br>"; var file = x.files[i]; if ('name' in file) { txt += "name: " + file.name + "<br>"; } if ('size' in file) { txt += "size: " + file.size + " bytes <br>"; } } } } else { if (x.value == "") { txt += "Select one or more files."; } else { txt += "The files property is not supported by your browser!"; txt += "<br>The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead. } } document.getElementById("demo").innerHTML = txt; } </script> <p><strong>Tip:</strong> Use the Control or the Shift key to select multiple files.</p> </body> </html>
執行結果