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
+49-49Lines changed: 49 additions & 49 deletions
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
+
Éste capítulo trata sobre el envío de formularios HTML: con o sin archivos, con campos adicionales y cosas similares.
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
+
Los objetos [FormData](https://xhr.spec.whatwg.org/#interface-formdata)pueden ser de ayuda en esta tarea. Tal como habrás supuesto, éste es el objeto encargado de representar los datos de los formularios HTML.
7
7
8
-
The constructor is:
8
+
El constructor es:
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
+
Si se le brinda un elemento HTML `form`, el objeto automáticamente capturará sus campos.
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
+
Lo que hace especial al objeto `FormData`es que los métodos de red, tales como`fetch`, pueden aceptar un objeto `FormData`como el cuerpo. Es codificado y enviado como`Content-Type: multipart/form-data`.
16
16
17
-
From the server point of view, that looks like a usual form submission.
17
+
Desde el punto de vista del servidor, se ve como una entrega normal.
18
18
19
-
## Sending a simple form
19
+
## Enviando un formulario simple
20
20
21
-
Let's send a simple form first.
21
+
Enviemos un formulario simple.
22
22
23
-
As you can see, that's almost one-liner:
23
+
Tal como se puede ver, es prácticamente una línea:
24
24
25
25
```html run autorun
26
26
<formid="formElem">
@@ -47,48 +47,48 @@ 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 beyound our scope. The server accepts the POST request and replies "User saved".
50
+
En este ejemplo, el código del servidor no es representado ya que está fuera de nuestro alcance. El servidor acepta le solicitud POST y responde "Usuario registrado".
51
51
52
-
## FormData Methods
52
+
## Métodos de FormData
53
53
54
-
We can modify fields in `FormData` with methods:
54
+
Contamos con métodos para poder modificar los campos del `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)` - agrega un campo al formulario con el nombre `name`y el valor`value`,
57
+
-`formData.append(name, blob, fileName)` - agrega un campo tal como si se tratara de un `<input type="file">`, el tercer argumento`fileName`establece el nombre del archivo (no el nombre del campo), tal como si se tratara del nombre del archivo en el sistema de archivos del usuario,
58
+
-`formData.delete(name)` - elimina el campo de nombre`name`,
59
+
-`formData.get(name)` - obtiene el valor del campo con el nombre`name`,
60
+
-`formData.has(name)` - en caso de que exista el campo con el nombre `name`, devuelve`true`, de lo contrario`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
+
Un formulario técnicamente tiene permitido contar con muchos campos con el mismo atributo `name`, por lo que múltiples llamadas a `append`agregarán más campos con el mismo nombre.
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
+
Por otra parte existe un método `set`, con la misma sintáxis que`append`. La diferencia está en que `.set`remueve todos los campos con el`name` que se le ha pasado, y luego agrega el nuevo campo. De este modo nos aseguramos de que sólo un campo éxiste con determinado `name`, el resto es tal como en`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
+
También es posible iterar por los campos del objeto formData utilizando un bucle `for..of`:
70
70
71
71
```js run
72
72
let formData =newFormData();
73
73
formData.append('key1', 'value1');
74
74
formData.append('key2', 'value2');
75
75
76
-
//List key/value pairs
76
+
//Se listan los pares clave/valor
77
77
for(let [name, value] of formData) {
78
-
alert(`${name} = ${value}`); // key1=value1, then key2=value2
78
+
alert(`${name} = ${value}`); // key1=value1, luego key2=value2
79
79
}
80
80
```
81
81
82
-
## Sending a form with a file
82
+
## Enviando un formulario con un archivo
83
83
84
-
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
+
El formulario siempre es enviado como`Content-Type: multipart/form-data`, esta codificación permite enviar archivos. Por lo tanto los campos `<input type="file">`también son enviados, tal como sucede en un envío normal.
@@ -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
+
## Enviando un formulario con datos 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
+
Tal como pudimos ver en el capítulo <info:fetch>, es fácil enviar datos binarios generados dinámicamente (por ejemplo una imagen) como`Blob`. Podemos proporcionarlos directamente en un `fetch`con el parámetro`body`.
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
+
De todos modos, en la práctica suele ser conveniente enviar la imagen como parte del formulario junto a otra metadata tal como el nombre y no de forma separada.
118
118
119
-
Also, servers are usually more suited to accept multipart-encoded forms, rather than raw binary data.
119
+
Además los servidores suelen ser más propensos a aceptar formularios multipart, en lugar de datos binarios sin procesar.
120
120
121
-
This example submits an image from `<canvas>`, along with some other fields, as a form, using`FormData`:
121
+
Este ejemplo envía una imagen desde un `<canvas>` junto con algunos campos más, como un formulario utilizando`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
+
Nota como la imagen `Blob`es agregada:
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
+
Es lo mismo que si hubiera un campo `<input type="file" name="image">`en el formulario, y el usuario enviara un archivo con nombre `"image.png"` (3er argumento) con los datos`imageBlob` (2do argumento) desde su sistema de archivos.
164
164
165
-
The server reads form data and the file, as if it were a regular form submission.
165
+
El servidor lee el formulario `form-data` y el archivo tal como si de un formulario regular se tratara.
166
166
167
-
## Summary
167
+
## Resumen
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
+
Los objetos [FormData](https://xhr.spec.whatwg.org/#interface-formdata)son utilizados para capturar un formulario HTML y enviarlo utilizando `fetch`u otro método de red.
170
170
171
-
We can either create `new FormData(form)`from an HTML form, or create a object without a form at all, and then append fields with methods:
171
+
Podemos crear el objeto con `new FormData(form)`desde un formulario HTML, o crearlo sin un formulario en absoluto, y agregar los campos con los siguientes métodos:
172
172
173
-
-`formData.append(name, value)`
174
-
-`formData.append(name, blob, fileName)`
175
-
-`formData.set(name, value)`
176
-
-`formData.set(name, blob, fileName)`
173
+
-`formData.append(nombre, valor)`
174
+
-`formData.append(nombre, blob, nombreDeArchivo)`
175
+
-`formData.set(nombre, valor)`
176
+
-`formData.set(nombre, blob, nombreDeArchivo)`
177
177
178
-
Let's note two peculiarities here:
178
+
Nótese aquí dos particularidades:
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.El método `set`remueve campos con el mismo nombre, mientras que `append`no. Esta es la única diferencia entre estos dos métodos.
181
+
2.Para enviar un archivo, se requiere de tres argumentos, el último argumento es el nombre del archivo, el cual normalmente es tomado desde el sistema de archivos del usuario por el`<input type="file">`.
0 commit comments