You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 5-network/02-formdata/article.md
+40-40
Original file line number
Diff line number
Diff line change
@@ -1,26 +1,26 @@
1
1
2
2
# FormData
3
3
4
-
This chapter is about sending HTML forms: with or without files, with additional fields and so on.
4
+
У цьому розділі йдеться про відправлення HTML-форм: з файлами та без, з додатковими полями й так далі.
5
5
6
-
[FormData](https://xhr.spec.whatwg.org/#interface-formdata)objects can help with that. As you might have guessed, it's the object to represent HTML form data.
6
+
Об’єкти [FormData](https://xhr.spec.whatwg.org/#interface-formdata)допоможуть нам із цим. Як ви, напевно, здогадалися за назвою, це об’єкт, що представляє дані HTML форми.
7
7
8
-
The constructor is:
8
+
Конструктор:
9
9
```js
10
10
let formData =newFormData([form]);
11
11
```
12
12
13
-
If HTML `form` element is provided, it automatically captures its fields.
13
+
Якщо передати в конструктор елемент HTML-форми`form`, то об’єкт, що створюється, автоматично прочитає з неї поля.
14
14
15
-
The special thing about `FormData` is that network methods, such as `fetch`, can accept a`FormData`object as a body. It's encoded and sent out with `Content-Type: multipart/form-data`.
15
+
Його особливість полягає в тому, що методи для роботи з мережею, наприклад, `fetch`, дозволяють вказати об’єкт`FormData`у властивості тіла запиту `body`.
16
16
17
-
From the server point of view, that looks like a usual form submission.
17
+
Тобто для сервера це виглядає як звичайне надсилання форми.
18
18
19
-
## Sending a simple form
19
+
## Надсилання простої форми
20
20
21
-
Let's send a simple form first.
21
+
Давайте спочатку надішлемо просту форму.
22
22
23
-
As you can see, that's almost one-liner:
23
+
Як ви бачите, код дуже компактний:
24
24
25
25
```html run autorun
26
26
<formid="formElem">
@@ -47,43 +47,43 @@ As you can see, that's almost one-liner:
47
47
</script>
48
48
```
49
49
50
-
In this example, the server code is not presented, as it's beyond our scope. The server accepts the POST request and replies "User saved".
50
+
У цьому прикладі серверний код не представлений, він за рамками цієї статті, він приймає POST-запит із даними форми та відповідає повідомленням «Користувач збережений».
51
51
52
-
## FormData Methods
52
+
## Методи об’єкта FormData
53
53
54
-
We can modify fields in `FormData` with methods:
54
+
За допомогою наведених нижче методів ми можемо змінювати поля в об’єкті `FormData`:
55
55
56
-
-`formData.append(name, value)` - add a form field with the given `name`and`value`,
57
-
-`formData.append(name, blob, fileName)` - add a field as if it were `<input type="file">`, the third argument `fileName`sets file name (not form field name), as it were a name of the file in user's filesystem,
58
-
-`formData.delete(name)` - remove the field with the given`name`,
59
-
-`formData.get(name)` - get the value of the field with the given`name`,
60
-
-`formData.has(name)` - if there exists a field with the given `name`, returns`true`, otherwise`false`
56
+
-`formData.append(name, value)` - додає до об’єкта поле з іменем `name`і значенням`value`,
57
+
-`formData.append(name, blob, fileName)` - додає поле так, ніби це `<input type="file">`, третій аргумент `fileName`встановлює ім’я файлу (не ім’я поля форми), ніби це ім’я з файлової системи користувача,
58
+
-`formData.delete(name)` - видаляє поле по заданому`name`,
59
+
-`formData.get(name)` - дістає значення поля по заданому`name`,
60
+
-`formData.has(name)` - перевіряє чи існує поле по заданому `name`, повертає`true`, інакше`false`
61
61
62
-
A form is technically allowed to have many fields with the same `name`, so multiple calls to `append`add more same-named fields.
62
+
Технічно форма може мати багато полів з тим самим ім’ям `name`, тому кілька викликів `append`додадуть кілька полів з однаковими іменами.
63
63
64
-
There's also method`set`, with the same syntax as `append`. The difference is that`.set`removes all fields with the given`name`, and then appends a new field. So it makes sure there's only one field with such `name`, the rest is just like `append`:
64
+
Ще існує метод`set`, його синтаксис такий самий, як у `append`. Різниця в тому, що`.set`видаляє всі наявні поля з ім'ям`name` і тільки потім додає нове. Тобто цей метод гарантує, що існуватиме лише одне поле з ім'ям `name`, у всьому іншому він аналогічний `.append`:
65
65
66
66
-`formData.set(name, value)`,
67
67
-`formData.set(name, blob, fileName)`.
68
68
69
-
Also we can iterate over formData fields using `for..of` loop:
69
+
Поля об’єкта `formData` можна перебирати, використовуючи цикл `for..of`:
The form is always sent as`Content-Type: multipart/form-data`, this encoding allows to send files. So, `<input type="file">`fields are sent also, similar to a usual form submission.
84
+
Об’єкти `FormData` завжди посилаються із заголовком`Content-Type: multipart/form-data`, цей спосіб кодування дозволяє надсилати файли. Таким чином, поля `<input type="file">`теж відправляються, як і при використанні разі звичайної форми.
85
85
86
-
Here's an example with such form:
86
+
Приклад такої форми:
87
87
88
88
```html run autorun
89
89
<formid="formElem">
@@ -110,15 +110,15 @@ Here's an example with such form:
110
110
</script>
111
111
```
112
112
113
-
## Sending a form with Blob data
113
+
## Надсилання форми з даними Blob
114
114
115
-
As we've seen in the chapter <info:fetch>, it's easy to send dynamically generated binary data e.g. an image, as`Blob`. We can supply it directly as `fetch` parameter `body`.
115
+
Раніше у главі <info:fetch> ми бачили, що дуже легко відправити динамічно згенеровані бінарні дані у форматі`Blob`. Ми можемо явно передати їх до параметра `body` запиту `fetch`.
116
116
117
-
In practice though, it's often convenient to send an image not separately, but as a part of the form, with additional fields, such as "name" and other metadata.
117
+
Але на практиці буває зручніше відправляти зображення не окремо, а у складі форми, додавши додаткові поля для імені та інші метадані.
118
118
119
-
Also, servers are usually more suited to accept multipart-encoded forms, rather than raw binary data.
119
+
Крім того, сервери часто налаштовані на приймання саме форм, а не просто бінарних даних.
120
120
121
-
This example submits an image from`<canvas>`, along with some other fields, as a form, using`FormData`:
121
+
У прикладі нижче надсилається зображення з`<canvas>` і ще кілька полів, як форма, використовуючи`FormData`:
122
122
123
123
```html run autorun height="90"
124
124
<bodystyle="margin:0">
@@ -154,36 +154,36 @@ This example submits an image from `<canvas>`, along with some other fields, as
154
154
</body>
155
155
```
156
156
157
-
Please note how the image `Blob` is added:
157
+
Будь ласка, зверніть увагу на те, як додається зображення `Blob`:
158
158
159
159
```js
160
160
formData.append("image", imageBlob, "image.png");
161
161
```
162
162
163
-
That's same as if there were `<input type="file" name="image">`in the form, and the visitor submitted a file named `"image.png"` (3rd argument) with the data `imageBlob` (2nd argument) from their filesystem.
163
+
Це як би у формі був елемент `<input type="file" name="image">`і користувач прикріпив би файл з ім’ям `"image.png"` (3й аргумент) та даними `imageBlob` (2й аргумент) зі своєї файлової системи.
164
164
165
-
The server reads form data and the file, as if it were a regular form submission.
165
+
Сервер прочитає і дані і файл, так само, якби це була звичайна відправка форми.
166
166
167
-
## Summary
167
+
## Підсумки
168
168
169
-
[FormData](https://xhr.spec.whatwg.org/#interface-formdata)objects are used to capture HTML form and submit it using`fetch`or another network method.
169
+
Об’єкти [FormData](https://xhr.spec.whatwg.org/#interface-formdata)використовуються, щоб взяти дані з HTML-форми та відправити їх за допомогою`fetch`або іншого методу для роботи з мережею.
170
170
171
-
We can either create `new FormData(form)` from an HTML form, or create an object without a form at all, and then append fields with methods:
171
+
Ми можемо створити такий об’єкт з даними, передавши в конструктор HTML-форму -- `new FormData(form)`, або ж можна створити об’єкт взагалі без форми і потім додати до нього поля за допомогою методів:
172
172
173
173
-`formData.append(name, value)`
174
174
-`formData.append(name, blob, fileName)`
175
175
-`formData.set(name, value)`
176
176
-`formData.set(name, blob, fileName)`
177
177
178
-
Let's note two peculiarities here:
178
+
Зазначимо дві особливості:
179
179
180
-
1.The`set`method removes fields with the same name, `append`doesn't. That's the only difference between them.
181
-
2.To send a file, 3-argument syntax is needed, the last argument is a file name, that normally is taken from user filesystem for `<input type="file">`.
180
+
1.Метод`set`видаляє поля з таким самим іменем, а `append`-- ні. У цьому їхня єдина відмінність.
181
+
2.Щоб надіслати файл, потрібно використовувати синтаксис з трьома аргументами, як третій вказується ім’я файлу, яке зазвичай, при `<input type="file">`, береться з файлової системи.
0 commit comments