В 2018 году веб-сайт, использующий простой JavaScript, может загружать файлы, как это делает Google Mail для почтовых вложений. Один клик может вызвать диалоговое окно обозревателя файлов в веб-браузере. Отдельная кнопка «Отправить» не нужна для начала загрузки. Хитрость заключается в использовании скрытого элемента HTML <input type="file">
.
Пример HTML и JavaScript:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File Upload</title>
<!-- Demo a button to upload files from a local computer to a web server. -->
</head>
<body>
<input type="file" id="inputFileElement" multiple style="display:none">
<button id="fileSelectButton">Select some files</button>
<script>
const fileSelectButton = document.getElementById("fileSelectButton");
const inputFileElement = document.getElementById("inputFileElement");
// When the user presses the upload button, simulate a click on the
// hidden <input type="file"> element so the web browser will show its
// file selection dialog.
fileSelectButton.addEventListener("click", function (e) {
if (inputFileElement) {
inputFileElement.click();
}
}, false);
// When the user selects one or more files on the local host,
// upload each file to the web server.
inputFileElement.addEventListener("change", handleFiles, false);
function handleFiles() {
const fileList = inputFileElement.files;
const numFiles = fileList.length;
for (let i = 0; i < numFiles; i++) {
const file = fileList[i];
console.log("Starting to upload " + file.name);
sendFile(file);
}
}
// Asynchronously read and upload a file.
function sendFile(file) {
const uri ="serverUpload.php";
const xhr = new XMLHttpRequest();
const fd = new FormData();
xhr.open("POST", uri, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log("Finished uploading: " + xhr.responseText); // handle response.
}
};
fd.append('myFile', file);
// Initiate a multipart/form-data upload
xhr.send(fd);
}
</script>
</body>
</html>
PHP код:
<?php
if (isset($_FILES['myFile'])) {
// Example:
move_uploaded_file($_FILES['myFile']['tmp_name'], "uploads/" . $_FILES['myFile']['name']);
echo $_FILES['myFile']['name'];
exit;
}
?>
Это работает в Internet Explorer 11, Edge, Firefox, Chrome, Opera.
Этот пример был получен из https://developer.mozilla.org/en-US/docs/Web/API/File/Using_files_from_web_applications
Индикатор выполнения см. Как получить прогресс из XMLHttpRequest