. Отсутствие этих ответов заключается в том, как получить диалог файла без входного элемента на странице.
Функция для отображения диалогового окна входного файла.
function openFileDialog (accept, callback) { // this function must be called from a user
// activation event (ie an onclick event)
// Create an input element
var inputElement = document.createElement("input");
// Set its type to file
inputElement.type = "file";
// Set accept to the file types you want the user to select.
// Include both the file extension and the mime type
inputElement.accept = accept;
// set onchange event to call callback when user has selected file
inputElement.addEventListener("change", callback)
// dispatch a click event to open the file dialog
inputElement.dispatchEvent(new MouseEvent("click"));
}
ПРИМЕЧАНИЕ. Функция должна быть частью активации пользователя, такого как событие click.
ПРИМЕЧАНИЕ
blockquote>input.accept
не используется в EdgeПример.
Вызов выше когда пользователь нажимает на якорный элемент.
// wait for window to load window.addEventListener("load", windowLoad); // open a dialog function function openFileDialog (accept, multy = false, callback) { var inputElement = document.createElement("input"); inputElement.type = "file"; inputElement.accept = accept; // Note Edge does not support this attribute if (multy) { inputElement.multiple = multy; } if (typeof callback === "function") { inputElement.addEventListener("change", callback); } inputElement.dispatchEvent(new MouseEvent("click")); } // onload event function windowLoad () { // add user click event to userbutton userButton.addEventListener("click", openDialogClick); } // userButton click event function openDialogClick () { // open file dialog for text files openFileDialog(".txt,text/plain", true, fileDialogChanged); } // file dialog onchange event handler function fileDialogChanged (event) { [...this.files].forEach(file => { var div = document.createElement("div"); div.className = "fileList common"; div.textContent = file.name; userSelectedFiles.appendChild(div); }); }
.common { font-family: sans-serif; padding: 2px; margin : 2px; border-radius: 4px; } .fileList { background: #229; color: white; } #userButton { background: #999; color: #000; width: 8em; text-align: center; cursor: pointer; } #userButton:hover { background : #4A4; color : white; }
<a id = "userButton" class = "common" title = "Click to open file selection dialog">Open file dialog</a> <div id = "userSelectedFiles" class = "common"></div>
Предупреждение о том, что приведенный выше фрагмент написан на ES6.