Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

File and FileReader#325

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
joaquinelio merged 23 commits intojavascript-tutorial:masterfromdaguitosama:file_n_file_reader
Aug 3, 2020
Merged
Changes fromall commits
Commits
Show all changes
23 commits
Select commitHold shift + click to select a range
6d26688
Update article.md
daguitosamaJul 26, 2020
e740ed2
Update article.md
daguitosamaJul 26, 2020
77db0a0
File and FileReader
daguitosamaJul 29, 2020
e5dc34e
Update 4-binary/04-file/article.md
vplentinaxJul 31, 2020
143cfe3
Update 4-binary/04-file/article.md
vplentinaxJul 31, 2020
ace97ff
Update 4-binary/04-file/article.md
daguitosamaAug 1, 2020
395da05
Update 4-binary/04-file/article.md
daguitosamaAug 1, 2020
2b1c0a3
Update 4-binary/04-file/article.md
daguitosamaAug 1, 2020
0a9e2c3
Update 4-binary/04-file/article.md
daguitosamaAug 1, 2020
f695ec6
Update 4-binary/04-file/article.md
daguitosamaAug 1, 2020
a182dfc
Update 4-binary/04-file/article.md
daguitosamaAug 1, 2020
e9d25b9
Update 4-binary/04-file/article.md
daguitosamaAug 1, 2020
ad5ba12
Update 4-binary/04-file/article.md
daguitosamaAug 1, 2020
7c96381
Update 4-binary/04-file/article.md
daguitosamaAug 1, 2020
8a71557
Update 4-binary/04-file/article.md
daguitosamaAug 2, 2020
8d3ba57
Update 4-binary/04-file/article.md
joaquinelioAug 3, 2020
739302d
Update 4-binary/04-file/article.md
joaquinelioAug 3, 2020
fad4a14
Update 4-binary/04-file/article.md
joaquinelioAug 3, 2020
f6842f3
Update 4-binary/04-file/article.md
joaquinelioAug 3, 2020
1734b55
Update 4-binary/04-file/article.md
joaquinelioAug 3, 2020
4d0a83a
Update 4-binary/04-file/article.md
joaquinelioAug 3, 2020
4c8eb82
Sincronizados los nros de linea
joaquinelioAug 3, 2020
73d6236
sincronizado nros linea 2da parte
joaquinelioAug 3, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 57 additions & 57 deletions4-binary/04-file/article.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,27 @@
# Fileand FileReader
# Filey FileReader

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

There are two ways to obtain it.
Hay dos maneras de obtenerlo

First, there's a constructor, similarto `Blob`:
Primero, hay un constructor, similaral de `Blob`:

```js
new File(fileParts, fileName, [options])
```

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

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

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

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

```html run
<input type="file" onchange="showFile(this)">
Expand All@@ -37,49 +37,49 @@ function showFile(input) {
```

```smart
The inputmay 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]`.
El inputpuede 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]`.
```

## FileReader

[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.
[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).

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

The constructor:
El constructor:

```js
let reader = new FileReader(); //no arguments
let reader = new FileReader(); //sin argumentos
```

The main methods:
Los métodos principales:

- **`readAsArrayBuffer(blob)`** --read the data in binary format `ArrayBuffer`.
- **`readAsText(blob, [encoding])`** --read the data as a text string with the given encoding (`utf-8` by default).
- **`readAsDataURL(blob)`** --read the binary data and encode it as base64 data url.
- **`abort()`** --cancel the operation.
- **`readAsArrayBuffer(blob)`** --lee los datos en formato binario `ArrayBuffer`.
- **`readAsText(blob, [codificación])`** --lee los datos como una cadena de texto con la codificación dada (por defecto es`utf-8`).
- **`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).
- **`abort()`** --cancela la operación.

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

- `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.
- `readAsText` --for text files, when we'd like to get a string.
- `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)`.
- `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.
- `readAsText` --para archivos de texto, cuando nesecitamos obtener una cadena.
- `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)`.

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

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

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

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

```html run
<input type="file" onchange="readFile(this)">
Expand All@@ -104,35 +104,35 @@ function readFile(input) {
</script>
```

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

We can use it to convert ablob to another format:
- `readAsArrayBuffer(blob)` --to `ArrayBuffer`,
- `readAsText(blob, [encoding])` --to string (an alternative to `TextDecoder`),
- `readAsDataURL(blob)` --to base64 data url.
Podemos usarlo para convertir un blob aotro formato:
- `readAsArrayBuffer(blob)` --a `ArrayBuffer`,
- `readAsText(blob, [encoding])` --a una cadena (una alternativa al `TextDecoder`),
- `readAsDataURL(blob)` --a Datos URI en base 64.
```


```smart header="`FileReaderSync`is available inside Web Workers"
ForWeb Workers, there also exists a synchronous variant of`FileReader`, called [FileReaderSync](https://www.w3.org/TR/FileAPI/#FileReaderSync).
```smart header="`FileReaderSync`está disponible dentro de Web Workers"
Para losWeb Workers también existe una variante síncrona de`FileReader` llamada [FileReaderSync](https://www.w3.org/TR/FileAPI/#FileReaderSync).

Its reading methods`read*`do not generate events, but rather return a result, as regular functions do.
Sus metodos`read*`no generan eventos sino que devuelven un resultado como las funciones regulares.

That's only inside aWeb 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.
Esto es solo dentro de unWeb 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.
```

##Summary
##Resumen

`File`objects inherit from `Blob`.
Los objetos`File`heredan de `Blob`.

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>`orDrag'n'Drop events (`ondragend`).
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 eventosDrag'n'Drop (`ondragend`).

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

In many cases though, we don't have to read the file contents. Just as we did withblobs,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.
En muchos casos no necesitamos leer el contenido de un archivo como hicimos con losblobs,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.

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.
Y si vamos a mandar un`File`por la red, es fácil utilizando APIs como`XMLHttpRequest`o `fetch`que aceptan nativamente objetos`File`.

[8]ページ先頭

©2009-2025 Movatter.jp