Как мы можем загрузить файл с помощью ajax-запроса с некоторыми дополнительными параметрами и индикатором выполнения.
И вопрос, и ответ должны стоять сами по себе, и в настоящее время вопрос слишком широк и неясен. Вы должны опубликовать ответ с вопросом, когда вы публикуете вопрос
@CertainPerformance Да, я отправил ответ на свой вопрос, из-за какой-то проблемы я не смог загрузить их одновременно, но теперь вы можете проверить мой ответ.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Мы можем сделать запрос ajax, используя основной JavaScript с XHR для загрузки файлов. Создайте следующие файлы:
/* ** upload.js ** */
var submit = document.getElementById('submit'),
file = document.getElementById('file'),
title = document.getElementById('title');
progress = document.getElementById('progress');
var upload = function(){
if (file.files.length === 0){
return;
}
var data = new FormData();
data.append('title', title.value);
data.append('SelectedFile', file.files[0]);
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if (request.readyState == 4){
try {
var resp = JSON.parse(request.response);
} catch (e){
var resp = {
status: 'error',
data: 'Unknown error occurred: [' + request.responseText + ']'
};
}
console.info(resp.status + ': ' + resp.data);
}
};
request.upload.addEventListener('progress', function(e){
var progress_width = Math.ceil(e.loaded/e.total * 100) + '%';
progress.style.width = progress_width;
}, false);
request.open('POST', 'save.php');
request.send(data);
}
submit.addEventListener('click', upload);/* ** style.css ** */
.container {
width: 500px;
margin: 0 auto;
}
.progress_outer {
border: 1px solid #000;
}
.progress {
width: 0%;
background: #DEDEDE;
height: 20px;
}<!-- ** index.html ** -->
<!doctype html>
<html>
<head>
<meta charset = "utf-8">
<title>JS File Upload with Progress</title>
<link rel = "stylesheet" href = "style.css">
</head>
<body>
<div class='container'>
<p>
Enter Title: <input type='text' id='title'>
</p>
<br/>
<p>
Select File: <input type='file' id='file'>
</p>
<br/>
<input type='button' id='submit' value='Upload File'>
<div class='progress_outer'>
<div id='progress' class='progress'></div>
</div>
</div>
<script src='upload.js'></script>
</body>
</html>Запустив приведенный выше код, вы получите значение поля файла и заголовка в вашем php-файле, как показано ниже:
print_r($_FILES); // for get file
print_r($_REQUEST); // for get additional fields
Выход
Array
(
[SelectedFile] => Array
(
[name] => 3400_1_1552283374.pdf
[type] => application/pdf
[tmp_name] => D:\xamp\tmp\php6D08.tmp
[error] => 0
[size] => 500320
)
)
Array
(
[title] => title
)
Спасибо @AmitKumar. Ваш ответ мне очень помог.
Я добавил этот вопрос, чтобы поделиться своим ответом на этот тип запросов.