Загрузка файлов на сервер с помощью JavaScript
Доброго времени суток! В данном примере я покажу Вам как можно загрузить файл на сервер с помощью JavaScript без перезагрузки страницы. Т.е. это так называемая AJAX загрузка.
Файл index.html (браузерная часть)
document
.querySelector(‘button[type=submit]’)
.addEventListener(‘click’, function(event)
// получаем элемент формы
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));
>);
>);
Файл upload.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.’;
> else return error(‘No file param’);
>
if (HttpMethod::GET === $httpMethod) return response([‘code’ => 200, ‘message’ => ‘No data’]);
>
>
Таким образом, можно загрузить файл на сервер с помощью технологии AJAX и PHP
Создано 01.11.2022 13:21:42
Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Порекомендуйте эту статью друзьям:
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
- Кнопка:
Она выглядит вот так: - Текстовая ссылка:
Она выглядит вот так: Как создать свой сайт - BB-код ссылки для форумов (например, можете поставить её в подписи):
Комментарии ( 0 ):
Для добавления комментариев надо войти в систему.
Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.
Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.
How to Upload Files with JavaScript
Austin Gil
I recently published a tutorial showing how to upload files with HTML. That’s great, but it’s a bit limited to using the native browser form behavior, which causes the page to refresh.
In this tutorial, I want to show you how to do the same thing with JavaScript to avoid the page refresh. That way, you can have the same functionality, but with better user experience.
How to Set Up an Event Handler
Let’s say you have an HTML form that looks like this:
With HTML, to access a file on the user’s device, we have to use an with the “file” type . And in order to create the HTTP request to upload the file, we have to use a element.
When dealing with JavaScript, the first part is still true. We still need the file input to access the files on the device. But browsers have a Fetch API that we can use to make HTTP requests without forms.
I still like to include a form because:
- Progressive enhancement: If JavaScript fails for whatever reason, the HTML form will still work.
- I’m lazy: The form will actually make my work easier later on, as we’ll see.
With that in mind, for JavaScript to submit this form, I’ll set up a “submit” event handler.
const form = document.querySelector('form'); form.addEventListener('submit', handleSubmit); /** @param event */ function handleSubmit(event) < // The rest of the logic will go here. >
Throughout the rest of this article, we’ll only be looking at the logic within the event handler function, handleSubmit .
How to Prepare the HTTP Request
The first thing I need to do in this submit handler is call the event’s preventDefault method to stop the browser from reloading the page to submit the form. I like to put this at the end of the event handler so that if there is an exception thrown within the body of this function, preventDefault will not be called, and the browser will fall back to the default behavior.
/** @param event */ function handleSubmit(event) < // Any JS that could fail goes here event.preventDefault(); >
Next, we’ll want to construct the HTTP request using the Fetch API. The Fetch API expects the first argument to be a URL, and a second, optional argument as an Object.
We can get the URL from the form’s action property. It’s available on any form DOM node which we can access using the event’s currentTarget property. If the action is not defined in the HTML, it will default to the browser’s current URL.
/** @param event */ function handleSubmit(event)
Relying on the HTML to define the URL makes it more declarative, keeps our event handler reusable, and our JavaScript bundles smaller. It also maintains functionality if the JavaScript fails.
By default, Fetch sends HTTP requests using the GET method, but to upload a file, we need to use a POST method. We can change the method using fetch ‘s optional second argument. I’ll create a variable for that object and assign the method property, but once again, I’ll grab the value from the form’s method attribute in the HTML.
const url = new URL(form.action); /** @type [1]> */ const fetchOptions = < method: form.method, >; fetch(url, fetchOptions);
Now the only missing piece is actually including the payload in the body of the request.
How to Add the Request Body
If you’ve ever created a Fetch request in the past, you may have included the body as a JSON string or a URLSearchParams object. Unfortunately, neither of those will work to send a file, as they don’t have access to the binary file contents.
Fortunately, there is the FormData browser API. We can use it to construct the request body from the form DOM node. And conveniently, when we do so, it even sets the request’s Content-Type header to multipart/form-data – also a necessary step to transmit the binary data.
const url = new URL(form.action); const formData = new FormData(form); /** @type [1]> */ const fetchOptions = < method: form.method, body: formData, >; fetch(url, fetchOptions);
That’s really the bare minimum needed to upload files with JavaScript. Let’s do a little recap:
- Access to the file system using a file type input.
- Construct an HTTP request using the Fetch (or XMLHttpRequest ) API.
- Set the request method to POST .
- Include the file in the request body.
- Set the HTTP Content-Type header to multipart/form-data .
Today we looked at a convenient way of doing that, using an HTML form element with a submit event handler, and using a FormData object in the body of the request. The current handleSumit function should look like this:
/** @param event */ function handleSubmit(event) < const url = new URL(form.action); const formData = new FormData(form); /** @type [1]> */ const fetchOptions = < method: form.method, body: formData, >; fetch(url, fetchOptions); event.preventDefault(); >
Unfortunately, the current submit handler is not very reusable. Every request will include a body set to a FormData object and a “ Content-Type ” header set to multipart/form-data . This is too brittle. Bodies are not allowed in GET requests, and we may want to support different content types in other POST requests.
How to Make it Reusable
We can make our code more robust to handle GET and POST requests, and send the appropriate Content-Type header. We’ll do so by creating a URLSearchParams object in addition to the FormData , and running some logic based on whether the request method should be POST or GET . I’ll try to lay out the logic below:
Is the request using a POST method?
— Yes: is the form’s enctype attribute multipart/form-data ?
— — Yes: set the body of the request to the FormData object. The browser will automatically set the “ Content-Type ” header to multipart/form-data .
— — No: set the body of the request to the URLSearchParams object. The browser will automatically set the “ Content-Type ” header to application/x-www-form-urlencoded .
— No: We can assume it’s a GET request. Modify the URL to include the data as query string parameters.
The refactored solution looks like:
/** @param event */ function handleSubmit(event) < /** @type */ const form = event.currentTarget; const url = new URL(form.action); const formData = new FormData(form); const searchParams = new URLSearchParams(formData); /** @type [1]> */ const fetchOptions = < method: form.method, >; if (form.method.toLowerCase() === 'post') < if (form.enctype === 'multipart/form-data') < fetchOptions.body = formData; >else < fetchOptions.body = searchParams; >> else < url.search = searchParams; >fetch(url, fetchOptions); event.preventDefault(); >
I really like this solution for a number of reasons:
- It can be used for any form.
- It relies on the underlying HTML as the declarative source of configuration.
- The HTTP request behaves the same as with an HTML form. This follows the principle of progressive enhancement, so file upload works the same when JavaScript is working properly or when it fails.
Thank you so much for reading. I hope you found this useful. If you liked this article, and want to support me, the best ways to do so are to share it, sign up for my newsletter, and follow me on Twitter.