Skip to content

Commit 287a5dc

Browse files
authored
Merge pull request #325 from d4g0/file_n_file_reader
File and FileReader
2 parents 06417d2 + 73d6236 commit 287a5dc

File tree

1 file changed

+57
-57
lines changed

1 file changed

+57
-57
lines changed

4-binary/04-file/article.md

Lines changed: 57 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,27 @@
1-
# File and FileReader
1+
# File y FileReader
22

3-
A [File](https://www.w3.org/TR/FileAPI/#dfn-file) object inherits from `Blob` and is extended with filesystem-related capabilities.
3+
Un [File](https://www.w3.org/TR/FileAPI/#dfn-file) hereda de `Blob` y extiende las capacidades relacionadas con el sistema de archivos.
44

5-
There are two ways to obtain it.
5+
Hay dos maneras de obtenerlo
66

7-
First, there's a constructor, similar to `Blob`:
7+
Primero, hay un constructor, similar al de `Blob`:
88

99
```js
1010
new File(fileParts, fileName, [options])
1111
```
1212

13-
- **`fileParts`** -- is an array of Blob/BufferSource/String values.
14-
- **`fileName`** -- file name string.
15-
- **`options`** -- optional object:
16-
- **`lastModified`** -- the timestamp (integer date) of last modification.
13+
- **`fileParts`** -- es un array con valores de tipo Blob/BufferSource/String.
14+
- **`fileName`** -- el nombre del archivo..
15+
- **`options`** -- objeto opcional:
16+
- **`lastModified`** -- la marca de tiempo (fecha en mili-segundos, de tipo entero) de la última modificación.
1717

18-
Second, more often we get a file from `<input type="file">` or drag'n'drop or other browser interfaces. In that case, the file gets this information from OS.
18+
Segundo, a menudo obtenemos un archivo mediante un `<input type="file">` o arrastrar y soltar u otras interfaces del navegador. En este caso el archivo obtiene la información del Sistema Operativo.
1919

20-
As `File` inherits from `Blob`, `File` objects have the same properties, plus:
21-
- `name` -- the file name,
22-
- `lastModified` -- the timestamp of last modification.
20+
Como `File` (Archivo) hereda de `Blob`, objetos de tipo `File` tienen las mismas propiedades, mas:
21+
- `name` -- el nombre del archivo,
22+
- `lastModified` -- la marca de tiempo de la última modificación.
2323

24-
That's how we can get a `File` object from `<input type="file">`:
24+
Así es como obtenemos un objeto `File` desde `<input type="file">` :
2525

2626
```html run
2727
<input type="file" onchange="showFile(this)">
@@ -37,49 +37,49 @@ function showFile(input) {
3737
```
3838

3939
```smart
40-
The input may select multiple files, so `input.files` is an array-like object with them. Here we have only one file, so we just take `input.files[0]`.
40+
El input puede seleccionar varios archivos, por lo que `input.files` es un array de dichos archivos . En este caso tenemos un solo archivo por lo que solo es necesario usar `input.files[0]`.
4141
```
4242

4343
## FileReader
4444

45-
[FileReader](https://www.w3.org/TR/FileAPI/#dfn-filereader) is an object with the sole purpose of reading data from `Blob` (and hence `File` too) objects.
45+
[FileReader](https://www.w3.org/TR/FileAPI/#dfn-filereader) es un objeto con el único porpósito de leer datos desde objetos de tipo `Blob` (por lo tanto `File` también).
4646

47-
It delivers the data using events, as reading from disk may take time.
47+
El entrega los datos usando eventos debido a que leerlos desde el disco puede tomar un tiempo.
4848

49-
The constructor:
49+
El constructor:
5050

5151
```js
52-
let reader = new FileReader(); // no arguments
52+
let reader = new FileReader(); // sin argumentos
5353
```
5454

55-
The main methods:
55+
Los métodos principales:
5656

57-
- **`readAsArrayBuffer(blob)`** -- read the data in binary format `ArrayBuffer`.
58-
- **`readAsText(blob, [encoding])`** -- read the data as a text string with the given encoding (`utf-8` by default).
59-
- **`readAsDataURL(blob)`** -- read the binary data and encode it as base64 data url.
60-
- **`abort()`** -- cancel the operation.
57+
- **`readAsArrayBuffer(blob)`** -- lee los datos en formato binario `ArrayBuffer`.
58+
- **`readAsText(blob, [codificación])`** -- lee los datos como una cadena de texto con la codificación dada (por defecto es `utf-8`).
59+
- **`readAsDataURL(blob)`** -- lee los datos binarios y los codifica como [Datos URIs] en base 64 (https://developer.mozilla.org/es/docs/Web/HTTP/Basics_of_HTTP/Datos_URIs).
60+
- **`abort()`** -- cancela la operación.
6161

62-
The choice of `read*` method depends on which format we prefer, how we're going to use the data.
62+
La opción del método `read*` depende de qué formato preferimos y cómo vamos a usar los datos.
6363

64-
- `readAsArrayBuffer` -- for binary files, to do low-level binary operations. For high-level operations, like slicing, `File` inherits from `Blob`, so we can call them directly, without reading.
65-
- `readAsText` -- for text files, when we'd like to get a string.
66-
- `readAsDataURL` -- when we'd like to use this data in `src` for `img` or another tag. There's an alternative to reading a file for that, as discussed in chapter <info:blob>: `URL.createObjectURL(file)`.
64+
- `readAsArrayBuffer` -- para archivos binarios, en donde se hacen operaciones binarias de bajo nivel. Para operaciones de alto nivel, como slicing, `File` hereda de `Blob` por lo que podemos llamarlas directamente sin tener que leer.
65+
- `readAsText` -- para archivos de texto, cuando nesecitamos obtener una cadena.
66+
- `readAsDataURL` -- cuando necesitamos usar estos datos como valores de `src` en `img` u otras etiquetas html. Hay otra alternativa para leer archivos de ese tipo como discutimos en el capítulo <info:blob>: `URL.createObjectURL(file)`.
6767

68-
As the reading proceeds, there are events:
69-
- `loadstart` -- loading started.
70-
- `progress` -- occurs during reading.
71-
- `load` -- no errors, reading complete.
72-
- `abort` -- `abort()` called.
73-
- `error` -- error has occurred.
74-
- `loadend` -- reading finished with either success or failure.
68+
Mientras se va realizando la lectura, suceden varios eventos:
69+
- `loadstart` -- la carga comenzó.
70+
- `progress` -- ocurre mientras se lee.
71+
- `load` -- lectura completada, sin errores.
72+
- `abort` -- `abort()` ha sido llamado.
73+
- `error` -- ha ocurrido un error .
74+
- `loadend` -- la lectura finalizó exitosa o no .
7575

76-
When the reading is finished, we can access the result as:
77-
- `reader.result` is the result (if successful)
78-
- `reader.error` is the error (if failed).
76+
Cuando la lectura finaliza, podemos acceder al resultado como:
77+
- `reader.result` el resultado (si fue exitoso)
78+
- `reader.error` el error (si hubo fallo).
7979

80-
The most widely used events are for sure `load` and `error`.
80+
Los mas ampliamente usados son seguramente `load` y `error`.
8181

82-
Here's an example of reading a file:
82+
Un ejemplo de como leer un archivo:
8383

8484
```html run
8585
<input type="file" onchange="readFile(this)">
@@ -104,35 +104,35 @@ function readFile(input) {
104104
</script>
105105
```
106106

107-
```smart header="`FileReader` for blobs"
108-
As mentioned in the chapter <info:blob>, `FileReader` can read not just files, but any blobs.
107+
```smart header="`FileReader` para blobs"
108+
Como mencionamos en el capítulo <info:blob>, `FileReader` no solo lee archivos sino también cualquier blob.
109109

110-
We can use it to convert a blob to another format:
111-
- `readAsArrayBuffer(blob)` -- to `ArrayBuffer`,
112-
- `readAsText(blob, [encoding])` -- to string (an alternative to `TextDecoder`),
113-
- `readAsDataURL(blob)` -- to base64 data url.
110+
Podemos usarlo para convertir un blob a otro formato:
111+
- `readAsArrayBuffer(blob)` -- a `ArrayBuffer`,
112+
- `readAsText(blob, [encoding])` -- a una cadena (una alternativa al `TextDecoder`),
113+
- `readAsDataURL(blob)` -- a Datos URI en base 64.
114114
```
115115
116116
117-
```smart header="`FileReaderSync` is available inside Web Workers"
118-
For Web Workers, there also exists a synchronous variant of `FileReader`, called [FileReaderSync](https://www.w3.org/TR/FileAPI/#FileReaderSync).
117+
```smart header="`FileReaderSync` está disponible dentro de Web Workers"
118+
Para los Web Workers también existe una variante síncrona de `FileReader` llamada [FileReaderSync](https://www.w3.org/TR/FileAPI/#FileReaderSync).
119119
120-
Its reading methods `read*` do not generate events, but rather return a result, as regular functions do.
120+
Sus metodos `read*` no generan eventos sino que devuelven un resultado como las funciones regulares.
121121
122-
That's only inside a Web Worker though, because delays in synchronous calls, that are possible while reading from files, in Web Workers are less important. They do not affect the page.
122+
Esto es solo dentro de un Web Worker, debido a que demoras en llamadas síncronas mientras se lee el archivo en Web Worker no son tan importantes. No afectan la página.
123123
```
124124

125-
## Summary
125+
## Resumen
126126

127-
`File` objects inherit from `Blob`.
127+
Los objetos `File` heredan de `Blob`.
128128

129-
In addition to `Blob` methods and properties, `File` objects also have `name` and `lastModified` properties, plus the internal ability to read from filesystem. We usually get `File` objects from user input, like `<input>` or Drag'n'Drop events (`ondragend`).
129+
Además de los métodos y propiedades de `Blob`, los objetos `File` también tienen las propiedades `name` y `lastModified` mas la habilidad interna de leer del sistema de archivos. Usualmente obtenemos los objetos `File` mediante la entrada del el usuario con `<input>` o eventos Drag'n'Drop (`ondragend`).
130130

131-
`FileReader` objects can read from a file or a blob, in one of three formats:
132-
- String (`readAsText`).
131+
Los objetos `FileReader` pueden leer desde un archivo o un blob en uno de estos tres formatos:
132+
- String (`readAsText`) .
133133
- `ArrayBuffer` (`readAsArrayBuffer`).
134-
- Data url, base-64 encoded (`readAsDataURL`).
134+
- Datos URI codificado en base 64 (`readAsDataURL`).
135135

136-
In many cases though, we don't have to read the file contents. Just as we did with blobs, we can create a short url with `URL.createObjectURL(file)` and assign it to `<a>` or `<img>`. This way the file can be downloaded or shown up as an image, as a part of canvas etc.
136+
En muchos casos no necesitamos leer el contenido de un archivo como hicimos con los blobs, podemos crear un enlace corto con `URL.createObjectURL(file)` y asignárselo a un `<a>` o `<img>`. De esta manera el archivo puede ser descargado, mostrado como una imagen o como parte de un canvas, etc.
137137

138-
And if we're going to send a `File` over a network, that's also easy: network API like `XMLHttpRequest` or `fetch` natively accepts `File` objects.
138+
Y si vamos a mandar un `File` por la red, es fácil utilizando APIs como `XMLHttpRequest` o `fetch` que aceptan nativamente objetos `File` .

0 commit comments

Comments
 (0)