Skip to content

Commit 0e6845b

Browse files
authored
Merge pull request #380 from kenliten/patch-1
Blob
2 parents 4b0357b + a29c5ef commit 0e6845b

File tree

1 file changed

+82
-82
lines changed

1 file changed

+82
-82
lines changed

4-binary/03-blob/article.md

Lines changed: 82 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -1,69 +1,69 @@
11
# Blob
22

3-
`ArrayBuffer` and views are a part of ECMA standard, a part of JavaScript.
3+
Los `ArrayBuffer` y las vistas son parte del estándar ECMA, una parte de JavaScript.
44

5-
In the browser, there are additional higher-level objects, described in [File API](https://www.w3.org/TR/FileAPI/), in particular `Blob`.
5+
En el navegador, hay objetos de alto nivel adicionales, descritas en la [API de Archivo](https://www.w3.org/TR/FileAPI/), en particular `Blob`.
66

7-
`Blob` consists of an optional string `type` (a MIME-type usually), plus `blobParts` -- a sequence of other `Blob` objects, strings and `BufferSource`.
7+
`Blob` consta de un tipo especial de cadena (usualmente de tipo MIME), más partes Blob: una secuencia de otros objetos `Blob`, cadenas y `BufferSource`.
88

99
![](blob.svg)
1010

11-
The constructor syntax is:
11+
La sintaxis del constructor es:
1212

1313
```js
14-
new Blob(blobParts, options);
14+
new Blob(blobParts, opciones);
1515
```
1616

17-
- **`blobParts`** is an array of `Blob`/`BufferSource`/`String` values.
18-
- **`options`** optional object:
19-
- **`type`** -- `Blob` type, usually MIME-type, e.g. `image/png`,
20-
- **`endings`** -- whether to transform end-of-line to make the `Blob` correspond to current OS newlines (`\r\n` or `\n`). By default `"transparent"` (do nothing), but also can be `"native"` (transform).
17+
- **`blobParts`** es un array de valores `Blob`/`BufferSource`/`String`.
18+
- **`opciones`** objeto opcional:
19+
- **`tipo`** -- `Blob`, usualmente un tipo MIME, por ej. `image/png`,
20+
- **`endings`** -- para transformar los finales de línea para hacer que el `Blob` coincida con los carácteres de nueva línea del Sistema Operativo actual (`\r\n` or `\n`). Por omisión es `"transparent"` (no hacer nada), pero también puede ser `"native"` (transformar).
2121

22-
For example:
22+
Por ejemplo:
2323

2424
```js
25-
// create Blob from a string
25+
// crear un Blob a partir de una cadena
2626
let blob = new Blob(["<html>…</html>"], {type: 'text/html'});
27-
// please note: the first argument must be an array [...]
27+
// observación: el primer argumento debe ser un array [...]
2828
```
2929

3030
```js
31-
// create Blob from a typed array and strings
32-
let hello = new Uint8Array([72, 101, 108, 108, 111]); // "Hello" in binary form
31+
// crear un Blob a partir de un array tipado y cadenas
32+
let hello = new Uint8Array([72, 101, 108, 108, 111]); // "Hello" en formato binario
3333

3434
let blob = new Blob([hello, ' ', 'world'], {type: 'text/plain'});
3535
```
3636

3737

38-
We can extract `Blob` slices with:
38+
Podemos extraer porciones del `Blob` con:
3939

4040
```js
4141
blob.slice([byteStart], [byteEnd], [contentType]);
4242
```
4343

44-
- **`byteStart`** -- the starting byte, by default 0.
45-
- **`byteEnd`** -- the last byte (exclusive, by default till the end).
46-
- **`contentType`** -- the `type` of the new blob, by default the same as the source.
44+
- **`byteStart`** -- el byte inicial, por omisión es 0.
45+
- **`byteEnd`** -- el último byte (exclusivo, por omisión es el final).
46+
- **`contentType`** -- el `tipo` del nuevo blob, por omisión es el mismo que la fuente.
4747

48-
The arguments are similar to `array.slice`, negative numbers are allowed too.
48+
Los argumentos son similares a `array.slice`, los números negativos también son permitidos.
4949

50-
```smart header="`Blob` objects are immutable"
51-
We can't change data directly in a `Blob`, but we can slice parts of a `Blob`, create new `Blob` objects from them, mix them into a new `Blob` and so on.
50+
```smart header="los objetos `Blob` son inmutables"
51+
No podemos cambiar datos directamente en un `Blob`, pero podemos obtener partes de un `Blob`, crear nuevos objetos `Blob` a partir de ellos, mezclarlos en un nuevo `Blob` y así por el estilo.
5252

53-
This behavior is similar to JavaScript strings: we can't change a character in a string, but we can make a new corrected string.
53+
Este comportamiento es similar a las cadenas de JavaScript: no podemos cambiar un caractér en una cadena, pero podemos hacer una nueva, corregida.
5454
```
5555
56-
## Blob as URL
56+
## Blob como URL
5757
58-
A Blob can be easily used as an URL for `<a>`, `<img>` or other tags, to show its contents.
58+
Un Blob puede ser utilizado fácilmente como una URL para `<a>`, `<img>` u otras etiquetas, para mostrar su contenido.
5959
60-
Thanks to `type`, we can also download/upload `Blob` objects, and the `type` naturally becomes `Content-Type` in network requests.
60+
Gracias al `tipo`, también podemos descargar/cargar objetos `Blob`, y el `tipo` se convierte naturalmente en `Content-Type` en solicitudes de red.
6161
62-
Let's start with a simple example. By clicking on a link you download a dynamically-generated `Blob` with `hello world` contents as a file:
62+
Empecemos con un ejemplo simple. Al hacer click en un link, descargas un `Blob` dinámicamente generado con contenido `hello world` en forma de archivo:
6363
6464
```html run
65-
<!-- download attribute forces the browser to download instead of navigating -->
66-
<a download="hello.txt" href='#' id="link">Download</a>
65+
<!-- descargar atributos forza el navegador a descargar en lugar de navegar -->
66+
<a download="hello.txt" href='#' id="link">Descargar</a>
6767
6868
<script>
6969
let blob = new Blob(["Hello, world!"], {type: 'text/plain'});
@@ -72,9 +72,9 @@ link.href = URL.createObjectURL(blob);
7272
</script>
7373
```
7474

75-
We can also create a link dynamically in JavaScript and simulate a click by `link.click()`, then download starts automatically.
75+
También podemos crear un link dinámicamente en JavaScript y simular un click con `link.click()`, y la descarga inicia automáticamente.
7676

77-
Here's the similar code that causes user to download the dynamicallly created `Blob`, without any HTML:
77+
Este es un código similar que permite al usuario descargar el `Blob` creado dinámicamente, sin HTML:
7878

7979
```js run
8080
let link = document.createElement('a');
@@ -89,50 +89,50 @@ link.click();
8989
URL.revokeObjectURL(link.href);
9090
```
9191

92-
`URL.createObjectURL` takes a `Blob` and creates a unique URL for it, in the form `blob:<origin>/<uuid>`.
92+
`URL.createObjectURL` toma un `Blob` y crea una URL única para él, con la forma `blob:<origin>/<uuid>`.
9393

94-
That's what the value of `link.href` looks like:
94+
Así es como se ve el valor de `link.href`:
9595

9696
```
9797
blob:https://javascript.info/1e67e00e-860d-40a5-89ae-6ab0cbee6273
9898
```
9999

100-
The browser for each URL generated by `URL.createObjectURL` stores an the URL -> `Blob` mapping internally. So such URLs are short, but allow to access the `Blob`.
100+
Por cada URL generada por `URL.createObjectURL` el navegador almacena un `Blob` en la URL mapeado internamente. Así que las URLs son cortas, pero permiten acceder al `Blob`.
101101

102-
A generated URL (and hence the link with it) is only valid within the current document, while it's open. And it allows to reference the `Blob` in `<img>`, `<a>`, basically any other object that expects an url.
102+
Una URL generada (y su relación con ella) solo es válida en el documento actual, mientras está abierto. Y este permite referenciar al `Blob` en `<img>`, `<a>`, básicamente cualquier otro objeto que espera un URL.
103103

104-
There's a side-effect though. While there's a mapping for a `Blob`, the `Blob` itself resides in the memory. The browser can't free it.
104+
También hay efectos secundarios. Mientras haya un mapeado para un `Blob`, el `Blob` en sí mismo se guarda en la memoria. El navegador no puede liberarlo.
105105

106-
The mapping is automatically cleared on document unload, so `Blob` objects are freed then. But if an app is long-living, then that doesn't happen soon.
106+
El mapeado se limpia automáticamente al vaciar un documento, así los objetos `Blob` son liberados. Pero si una applicación es de larga vida, entonces eso no va a pasar pronto.
107107

108-
**So if we create a URL, that `Blob` will hang in memory, even if not needed any more.**
108+
**Entonces, si creamos una URL, este `Blob` se mantendrá en la memoria, incluso si ya no se necesita.**
109109

110-
`URL.revokeObjectURL(url)` removes the reference from the internal mapping, thus allowing the `Blob` to be deleted (if there are no other references), and the memory to be freed.
110+
`URL.revokeObjectURL(url)` elimina la referencia el mapeo interno, además de permitir que el `Blob` sea borrado (si ya no hay otras referencias), y que la memoria sea liberada.
111111

112-
In the last example, we intend the `Blob` to be used only once, for instant downloading, so we call `URL.revokeObjectURL(link.href)` immediately.
112+
En el último ejemplo, intentamos que el `Blob` sea utilizado una sola vez, para descargas instantáneas, así llamamos `URL.revokeObjectURL(link.href)` inmediatamente.
113113

114-
In the previous example with the clickable HTML-link, we don't call `URL.revokeObjectURL(link.href)`, because that would make the `Blob` url invalid. After the revocation, as the mapping is removed, the URL doesn't work any more.
114+
En el ejemplo anterior con el link HTML clickeable, no llamamos `URL.revokeObjectURL(link.href)`, porque eso puede hacer la URL del `Blob` inválido. Después de la revocación, como el mapeo es eliminado, la URL ya no volverá a funcionar.
115115

116-
## Blob to base64
116+
## Blob a base64
117117

118-
An alternative to `URL.createObjectURL` is to convert a `Blob` into a base64-encoded string.
118+
Una alternativa a `URL.createObjectURL` es convertir un `Blob` en una cadena codificada en base64.
119119

120-
That encoding represents binary data as a string of ultra-safe "readable" characters with ASCII-codes from 0 to 64. And what's more important -- we can use this encoding in "data-urls".
120+
Esa codificación representa datos binarios como una cadena ultra segura de caractéres "legibles" con códigos ASCII desde el 0 al 64. Y lo que es más importante, podemos utilizar codificación en las "URLs de datos".
121121

122-
A [data url](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) has the form `data:[<mediatype>][;base64],<data>`. We can use such urls everywhere, on par with "regular" urls.
122+
Un [URL de datos](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) tiene la forma `data:[<mediatype>][;base64],<data>`. Podemos usar suficientes URLs por doquier, junto a URLs "regulares".
123123

124-
For instance, here's a smiley:
124+
Por ejemplo, aquí hay una sonrisa:
125125

126126
```html
127127
<img src="data:image/png;base64,R0lGODlhDAAMAKIFAF5LAP/zxAAAANyuAP/gaP///wAAAAAAACH5BAEAAAUALAAAAAAMAAwAAAMlWLPcGjDKFYi9lxKBOaGcF35DhWHamZUW0K4mAbiwWtuf0uxFAgA7">
128128
```
129129

130-
The browser will decode the string and show the image: <img src="data:image/png;base64,R0lGODlhDAAMAKIFAF5LAP/zxAAAANyuAP/gaP///wAAAAAAACH5BAEAAAUALAAAAAAMAAwAAAMlWLPcGjDKFYi9lxKBOaGcF35DhWHamZUW0K4mAbiwWtuf0uxFAgA7">
130+
El navegador decodificará la cadena y mostrará la imagen: <img src="data:image/png;base64,R0lGODlhDAAMAKIFAF5LAP/zxAAAANyuAP/gaP///wAAAAAAACH5BAEAAAUALAAAAAAMAAwAAAMlWLPcGjDKFYi9lxKBOaGcF35DhWHamZUW0K4mAbiwWtuf0uxFAgA7">
131131

132132

133-
To transform a `Blob` into base64, we'll use the built-in `FileReader` object. It can read data from Blobs in multiple formats. In the [next chapter](info:file) we'll cover it more in-depth.
133+
Para transformar un `Blob` a base64, usaremos el objeto nativo `FileReader`. Puede leer datos de Blobs en múltiples formatos. En el [siguiente capítulo](info:file) lo cubriremos en profundidad.
134134

135-
Here's the demo of downloading a blob, now via base-64:
135+
Aquí está el demo de descarga de un blob, ahora con base-64:
136136

137137
```js run
138138
let link = document.createElement('a');
@@ -142,79 +142,79 @@ let blob = new Blob(['Hello, world!'], {type: 'text/plain'});
142142

143143
*!*
144144
let reader = new FileReader();
145-
reader.readAsDataURL(blob); // converts the blob to base64 and calls onload
145+
reader.readAsDataURL(blob); // convierte el blob a base64 y llama a onload
146146
*/!*
147147

148148
reader.onload = function() {
149-
link.href = reader.result; // data url
149+
link.href = reader.result; // URL de datos
150150
link.click();
151151
};
152152
```
153153

154-
Both ways of making an URL of a `Blob` are usable. But usually `URL.createObjectURL(blob)` is simpler and faster.
154+
Se pueden utilizar ambas maneras para hacer una URL de un `Blob` . Pero usualmente `URL.createObjectURL(blob)` es más simple y rápido.
155155

156-
```compare title-plus="URL.createObjectURL(blob)" title-minus="Blob to data url"
157-
+ We need to revoke them if care about memory.
158-
+ Direct access to blob, no "encoding/decoding"
159-
- No need to revoke anything.
160-
- Performance and memory losses on big `Blob` objects for encoding.
156+
```compare title-plus="URL.createObjectURL(blob)" title-minus="Blob a URL de datos"
157+
+ Necesitamos revocarlos para cuidar la memoria.
158+
+ Acceso directo al blob, sin "condificación/decodificación"
159+
- No necesitamos revocar nada.
160+
- Se pierde rendimiento y memoria en grandes objetos `Blob` al codificar.
161161
```
162162

163-
## Image to blob
163+
## imagen a blob
164164

165-
We can create a `Blob` of an image, an image part, or even make a page screenshot. That's handy to upload it somewhere.
165+
Podemos crear un `Blob` de una imagen, una parte de una imagen, o incluso hacer una captura de la página. Es práctico para subirlo a algún lugar.
166166

167-
Image operations are done via `<canvas>` element:
167+
Las operaciones de imágenes se hacen a través del elemento `<canvas>`:
168168

169-
1. Draw an image (or its part) on canvas using [canvas.drawImage](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage).
170-
2. Call canvas method [.toBlob(callback, format, quality)](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob) that creates a `Blob` and runs `callback` with it when done.
169+
1. Dibuja una imagen (o una parte) en el canvas utilizando [canvas.drawImage](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage).
170+
2. Llama el método de canvas [.toBlob(callback, format, quality)](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob) que crea un `Blob` y llama el `callback` cuando termina.
171171

172-
In the example below, an image is just copied, but we could cut from it, or transform it on canvas prior to making a blob:
172+
En el ejemplo siguiente, un imagen se copia, pero no podemos cortarla o transformarla en el canvas hasta convertirla en blob:
173173

174174
```js run
175-
// take any image
175+
// tomar cualquier imagen
176176
let img = document.querySelector('img');
177177

178-
// make <canvas> of the same size
178+
// hacer el <canvas> del mismo tamaño
179179
let canvas = document.createElement('canvas');
180180
canvas.width = img.clientWidth;
181181
canvas.height = img.clientHeight;
182182

183183
let context = canvas.getContext('2d');
184184

185-
// copy image to it (this method allows to cut image)
185+
// copiar la imagen en él (este método permite cortar la imagen)
186186
context.drawImage(img, 0, 0);
187-
// we can context.rotate(), and do many other things on canvas
187+
// podemos hacer un context.rotate(), y muchas otras cosas en canvas
188188

189-
// toBlob is async opereation, callback is called when done
189+
// toBlob es una operación sincrónica, callback es llamada al terminar
190190
canvas.toBlob(function(blob) {
191-
// blob ready, download it
191+
// blob listo, descárgalo
192192
let link = document.createElement('a');
193193
link.download = 'example.png';
194194

195195
link.href = URL.createObjectURL(blob);
196196
link.click();
197197

198-
// delete the internal blob reference, to let the browser clear memory from it
198+
// borrar la referencia interna del blob, para permitir al navegador eliminarlo de la memoria
199199
URL.revokeObjectURL(link.href);
200200
}, 'image/png');
201201
```
202202

203-
If we prefer `async/await` instead of callbacks:
203+
Si preferimos `async/await` en lugar de callbacks:
204204
```js
205205
let blob = await new Promise(resolve => canvasElem.toBlob(resolve, 'image/png'));
206206
```
207207

208-
For screenshotting a page, we can use a library such as <https://github.com/niklasvh/html2canvas>. What it does is just walks the page and draws it on `<canvas>`. Then we can get a `Blob` of it the same way as above.
208+
Para capturar la página, podemos utilizar una librería como <https://github.com/niklasvh/html2canvas>. Que lo que hace es escanear toda la página y dibujarla en el `<canvas>`. Entonces podemos obtener un `Blob` de la misma manera que arriba.
209209

210-
## From Blob to ArrayBuffer
210+
## De Blob a ArrayBuffer
211211

212-
The `Blob` constructor allows to create a blob from almost anything, including any `BufferSource`.
212+
El constructor de `Blob` permite crear un blob de casi cualquier cosa, incluyendo cualquier `BufferSource`.
213213

214-
But if we need to perform low-level processing, we can get the lowest-level `ArrayBuffer` from it using `FileReader`:
214+
Pero si queremos ejecutar un procesamiento de bajo nivel, podemos obtener el nivel más bajo de un `ArrayBuffer` utilizando `FileReader`:
215215

216216
```js
217-
// get arrayBuffer from blob
217+
// obtener un arrayBuffer desde un blob
218218
let fileReader = new FileReader();
219219

220220
*!*
@@ -227,15 +227,15 @@ fileReader.onload = function(event) {
227227
```
228228

229229

230-
## Summary
230+
## Resumen
231231

232-
While `ArrayBuffer`, `Uint8Array` and other `BufferSource` are "binary data", a [Blob](https://www.w3.org/TR/FileAPI/#dfn-Blob) represents "binary data with type".
232+
Mientras `ArrayBuffer`, `Uint8Array` y otros `BufferSource` son "datos binarios", un [Blob](https://www.w3.org/TR/FileAPI/#dfn-Blob) representa "datos binarios con tipo".
233233

234-
That makes Blobs convenient for upload/download operations, that are so common in the browser.
234+
Esto hace a los Blobs convenientes para operaciones de carga/descarga, estos son muy comunes en el navegador.
235235

236-
Methods that perform web-requests, such as [XMLHttpRequest](info:xmlhttprequest), [fetch](info:fetch) and so on, can work with `Blob` natively, as well as with other binary types.
236+
Los métodos que ejecutan solicitudes web, como [XMLHttpRequest](info:xmlhttprequest), [fetch](info:fetch) y otros, pueden trabajar nativamente con `Blob`, como con otros tipos binarios.
237237

238-
We can easily convert betweeen `Blob` and low-level binary data types:
238+
Podemos convertir fácilmente entre `Blob` y tipos de datos binarios de bajo nivel:
239239

240-
- We can make a Blob from a typed array using `new Blob(...)` constructor.
241-
- We can get back `ArrayBuffer` from a Blob using `FileReader`, and then create a view over it for low-level binary processing.
240+
- Podemos convertir a Blob desde un array tipado usando el constructor `new Blob(...)`.
241+
- Podemos obtener un `ArrayBuffer` de un Blob usando `FileReader`, y entonces crear una vista sobre él para procesamiento binario de bajo nivel.

0 commit comments

Comments
 (0)