Загрузка файлов на сервер с помощью JavaScript
Доброго времени суток! В данном примере я покажу Вам как можно загрузить файл на сервер с помощью JavaScript без перезагрузки страницы. Т.е. это так называемая AJAX загрузка.
Файл index.html (браузерная часть)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JS Ajax File Upload</title>
</head>
<body>
<div id="example">
<form enctype="multipart/form-data" action="http://localhost:8080/upload" method="post">
<input name="profileImage" type="file">
<button type="submit">Сохранить!</button>
</form>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
document
.querySelector('button[type=submit]')
.addEventListener('click', function(event) {
event.preventDefault();
// получаем элемент формы
const form = this.form;
// создаем объект данных формы
const data = new FormData(form);
// получаем url-адрес на которые будем отправлять запрос
const url = form.action;
// отправляем запрос
fetch(url, {
method: 'POST',
// headers: {
// 'Content-Type': 'multipart/form-data'
// },
body: data,
})
.then(res => res.json())
.then(data => console.log(data.message));
});
});
</script>
</body>
</html>
Файл upload.php (серверная часть)
<?php
const FILES_STORAGE_PATH = './uploaded';
interface HttpMethod
{
public const GET = 'GET';
public const POST = 'POST';
}
function response(mixed $data)
{
return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
}
function ok(array $data)
{
return response(array_merge(['code' => 200], $data));
}
function error(string $message)
{
return response(['code' => 500, 'message' => $message]);
}
function notfound()
{
return response(['code' => 404, 'message' => 'Not found']);
}
function main()
{
$httpPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$httpMethod = $_SERVER['REQUEST_METHOD'];
$allowedExtensions = ['txt', 'pdf', 'png', 'jpg'];
header('Access-Control-Allow-Origin: *');
header('Content-Type: appplication/json');
if (HttpMethod::POST === $httpMethod) {
if ('/upload' === $httpPath) {
if (isset($_FILES['profileImage']))
{
$tmpName = $_FILES['profileImage']['tmp_name'];
$clientName = $_FILES['profileImage']['name'];
$extension = pathinfo($clientName, PATHINFO_EXTENSION);
$serverName = sprintf("%s/%s.%s", FILES_STORAGE_PATH, md5($clientName), $extension);
$uploadErrorCode = $_FILES['profileImage']['error'];
if(!in_array($extension, $allowedExtensions, 1)) {
return error('Extension not allowed');
}
if(move_uploaded_file($tmpName, $serverName))
{
return ok(['message' => 'File uploaded', 'filename' => $serverName]);
}
else if($uploadErrorCode > 0)
{
$fileUploadErrorsMap = [
UPLOAD_ERR_INI_SIZE => 'The file exceeds the upload_max_filesize setting in php.ini.',
UPLOAD_ERR_FORM_SIZE => 'The file exceeds the MAX_FILE_SIZE setting in the HTML form.',
UPLOAD_ERR_PARTIAL => 'The file was only partially uploaded.',
UPLOAD_ERR_NO_FILE => 'No file was uploaded.',
UPLOAD_ERR_NO_TMP_DIR => 'No temporary folder was available.',
UPLOAD_ERR_CANT_WRITE => 'Unable to write to the disk.',
UPLOAD_ERR_EXTENSION => 'File upload stopped.'
];
$errorMessage = $fileUploadErrorsMap[$uploadErrorCode] ?: 'A system error occurred.';
return error($errorMessage);
}
} else {
return error('No file param');
}
} else {
return notfound();
}
}
if (HttpMethod::GET === $httpMethod) {
return response(['code' => 200, 'message' => 'No data']);
}
}
print main();
Таким образом, можно загрузить файл на сервер с помощью технологии AJAX и PHP