Skip to content

Commit bc8c3ea

Browse files
authored
Merge pull request #295 from longo-andrea/article/blob
Blob
2 parents 082f738 + 571b8ec commit bc8c3ea

File tree

1 file changed

+80
-79
lines changed

1 file changed

+80
-79
lines changed

4-binary/03-blob/article.md

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

3-
`ArrayBuffer` and views are a part of ECMA standard, a part of JavaScript.
3+
Gli `ArrayBuffer` e i visualizzatori fanno parte dello standard ECMA; sono quindi parte di 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+
Nei browser, abbiamo a disposizione degli oggetti più ad alto livello, descritti in [File API](https://www.w3.org/TR/FileAPI/), in particolare l'oggetto `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+
L'oggetto `Blob` consiste di una stringa opzionale `type` (solitamente di tipo MIME), e di `blobParts`, una sequenza di oggetti `Blob`, stringhe e `BufferSource`.
88

99
![](blob.svg)
1010

11-
The constructor syntax is:
11+
La sintassi da utilizzare per costruire l'oggetto:
1212

1313
```js
1414
new Blob(blobParts, options);
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`** è un array di valori di tipo `Blob`/`BufferSource`/`String`.
18+
- **`options`** oggetto opzionale:
19+
- **`type`**, di tipo `Blob`, solitamente di tipo MIME, e.g. `image/png`,
20+
- **`endings`**, se trasformare il carattere di fine riga per far sì che il `Blob` contenga il carattere nuova riga del Sistema Operativo corrente (`\r\n` o `\n`). Di default è `"transparent"` (non fa nulla), ma può assumere il valore `"native"` (effettua la trasformazione).
2121

22-
For example:
22+
Ad esempio:
2323

2424
```js
25-
// create Blob from a string
25+
// creiamo un Blob partendo da una stringa
2626
let blob = new Blob(["<html>…</html>"], {type: 'text/html'});
27-
// please note: the first argument must be an array [...]
27+
// da notare: il primo argomento deve essere 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+
// creiamo un Blob partendo da un TypedArray e da due stringhe
32+
let hello = new Uint8Array([72, 101, 108, 108, 111]); // "Hello" nella forma binaria
3333

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

3737

38-
We can extract `Blob` slices with:
38+
Possiamo estrarre le parti 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`** - il byte di partenza, di default 0.
45+
- **`byteEnd`** - l'ultimo byte (escluso, fino alla fine di default).
46+
- **`contentType`** - il `type` del nuovo blob, di default lo stesso di quello di origine.
4747

48-
The arguments are similar to `array.slice`, negative numbers are allowed too.
48+
Gli argomenti sono simili al metodo `array.slice`; sono ammessi anche i valori negativi.
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="Gli oggetti `Blob` sono immutabili"
51+
Non possiamo modificare direttamente i dati di un `Blob`, ma possiamo estrarne delle parti, utilizzarle per creare nuovi `Blob`, fonderle insieme in un unico `Blob`, e molto altro.
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+
Questo comportamento è simile alle stringhe JavaScript: non possiamo modificare direttamente un carattere in una stringa, ma possiamo creare una nuova stringa modificata.
5454
```
5555
56-
## Blob as URL
56+
## Blob come URL
5757
58-
A Blob can be easily used as a URL for `<a>`, `<img>` or other tags, to show its contents.
58+
Un `Blob` può essere utilizzato facilmente come URL per `<a>`, `<img>` o altri tag, per mostrarne i contenuti.
5959
60-
Thanks to `type`, we can also download/upload `Blob` objects, and the `type` naturally becomes `Content-Type` in network requests.
60+
Grazie alla proprietà `type`, possiamo anche effettuare download/upload di `Blob`, ed il `type`, naturalmente, diventerà il `Content-Type` nelle richieste network.
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+
Iniziamo con un semplice esempio. Cliccando sul link verrà scaricato come file un `Blob` generato dinamicamente, contenente `hello world`:
6363
6464
```html run
65-
<!-- download attribute forces the browser to download instead of navigating -->
65+
<!-- l'attributo download forza il browser ad effettuare il download anziché navigare -->
6666
<a download="hello.txt" href='#' id="link">Download</a>
6767
6868
<script>
@@ -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+
Possiamo anche creare dinamicamente un link in JavaScript e simularne il click con `link.click()`, in questo modo il download inizierà automaticamente.
7676

77-
Here's the similar code that causes user to download the dynamically created `Blob`, without any HTML:
77+
Qui vediamo il codice che effettua il download del `Blob` generato dinamicamente, senza alcun 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` accetta come parametro un `Blob` e ne crea un corrispondente URL univoco, nella forma `blob:<origin>/<uuid>`.
9393

94-
That's what the value of `link.href` looks like:
94+
Questo è un esempio di come potrebbe apparire il valore di un `link.href`:
9595

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

100-
For each URL generated by `URL.createObjectURL` the browser stores a URL -> `Blob` mapping internally. So such URLs are short, but allow to access the `Blob`.
100+
Per ogni URL generato da `URL.createObjectURL` il browser memorizza in una mappa interna la coppia URL -> `Blob`. Così da rendere questi URL più corti, ma in grado di fornire comunque l'accesso 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 a URL.
102+
Un URL generato (e quindi anche il suo link) è valido solamente all'interno del `document` corrente, finché questo rimane aperto. E può essere utilizzato per fare riferimento al `Blob` nei tag `<img>`, `<a>`, e qualsiasi altro oggetto che accetta 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+
Abbiamo però un effetto collaterale. Poiché i `Blob` sono mappati, ogni oggetto `Blob` risiede in memoria. Quindi il browser non potrà liberarla.
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+
La mappa verrà automaticamente ripulita al momento dell'`unload` del `document`, quindi gli oggetti di `Blob` verranno eliminati in quel momento. Ma nel caso di applicazioni che "vivono a lungo", questa pulizia non avverrà presto.
107107

108-
**So if we create a URL, that `Blob` will hang in memory, even if not needed any more.**
108+
**Quindi se creiamo un URL, il relativo `Blob` rimarrà in memoria, anche se non è più necessario.**
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)` rimuove il riferimento dalla mappa interna, in questo modo sarà possibile eliminare i `Blob` (se questi non possiedono più alcun riferimento), e liberare la memoria.
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+
Nell'ultimo esempio, il nostro intento era di utilizzare il `Blob` solamente una volta, per il download istantaneo, quindi possiamo invocare `URL.revokeObjectURL(link.href)` immediatamente.
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+
Nell'esempio precedente, con il link HTML cliccabile, non invochiamo `URL.revokeObjectURL(link.href)`, poiché questo renderebbe l'URL del `Blob` invalido. Dopo averlo revocato, la coppia URL-`Blob` verrà rimossa dalla mappa, e l'URL non funzionerà più.
115115

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

118-
An alternative to `URL.createObjectURL` is to convert a `Blob` into a base64-encoded string.
118+
Un alternativa a `URL.createObjectURL` è quella di convertire un `Blob` in una stringa codificata in base 64.
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+
Questo tipo di encoding rappresenta i dati binari come una stringa leggibile di caratteri ultra-safe, con caratteri ASCII-code da 0 a 64. E, molto più importante, possiamo utilizzare questo encoding nei "data-urls".
121121

122-
A [data url](mdn:/http/Data_URIs) has the form `data:[<mediatype>][;base64],<data>`. We can use such urls everywhere, on par with "regular" urls.
122+
Un [data url](mdn:/http/Data_URIs) è rappresentato nella forma `data:[<mediatype>][;base64],<data>`. Possiamo utilizzare questi URL ovunque, in alternativa agli URL "regolari".
123123

124-
For instance, here's a smiley:
124+
Ad esempio, qui vediamo un sorriso:
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+
Il browser decodificherà la stringa e mostrerà l'immagine: <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+
Per trasformare un `Blob` in base64, utilizzeremo l'oggetto integrato `FileReader`. Può leggere dati da un Blob in diversi formati. Nel [prossimo capitolo](info:file) lo vedremo più in dettaglio.
134134

135-
Here's the demo of downloading a blob, now via base-64:
135+
Qui vediamo un esempio di download di un Blob, utilizzando la base-64:
136136

137137
```js run
138138
let link = document.createElement('a');
@@ -142,7 +142,7 @@ 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); // convertiamo il Blob in base64 e invochiamo onload
146146
*/!*
147147

148148
reader.onload = function() {
@@ -151,70 +151,71 @@ reader.onload = function() {
151151
};
152152
```
153153

154-
Both ways of making a URL of a `Blob` are usable. But usually `URL.createObjectURL(blob)` is simpler and faster.
154+
Entrambi i modi per costruire un URL corrispondente ad un `Blob` sono utilizzabili. Solitamente `URL.createObjectURL(blob)` è più semplice e veloce.
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="Da Blob a data url"
157+
+ Dobbiamo revocarli per mantenere pulita la memoria.
158+
+ Accesso diretto al Blob, no "encoding/decoding".
159+
- Non dobbiamo ricordarci di revocare nulla.
160+
- Abbiamo perdite di performance e memoria su grandi oggetti di tipo `Blob` a causa dell'encoding.
161161
```
162162

163-
## Image to blob
163+
## Da image 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+
Possiamo creare un `Blob` relativo ad un immagine, o addirittura fare uno screenshot della pagina. Può essere molto utile se abbiamo la necessità di caricarla da qualche parte.
166166

167-
Image operations are done via `<canvas>` element:
167+
Le operazioni sulle immagini sono fatte tramite l'elemento `<canvas>`:
168168

169-
1. Draw an image (or its part) on canvas using [canvas.drawImage](mdn:/api/CanvasRenderingContext2D/drawImage).
170-
2. Call canvas method [.toBlob(callback, format, quality)](mdn:/api/HTMLCanvasElement/toBlob) that creates a `Blob` and runs `callback` with it when done.
169+
1. Disegniamo un'immagine (o una usa parte) su un canvas utilizziando [canvas.drawImage](mdn:/api/CanvasRenderingContext2D/drawImage).
170+
2. Invochiamo il metodo sui canvas [.toBlob(callback, format, quality)](mdn:/api/HTMLCanvasElement/toBlob) il quale crea un `Blob` ed esegue la `callback` al termine dell'operazione.
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+
Nell'esempio sotto, un'immagine è appena stata copiata, ma potremmo volerla tagliare, o trasformarla utilizzando un canvas, prima di creare un blob:
173173

174174
```js run
175-
// take any image
175+
// prendiamo un'immagine
176176
let img = document.querySelector('img');
177177

178-
// make <canvas> of the same size
178+
// creiamo un <canvas> delle stesse dimensioni
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+
// ci copiamo l'immagine al suo interno (questo metodo consente di tagliare l'immagine)
186186
context.drawImage(img, 0, 0);
187-
// we can context.rotate(), and do many other things on canvas
187+
// possiamo context.rotate(), ed effettuare molte altre operazioni tramite il canvas
188188

189-
// toBlob is async operation, callback is called when done
189+
190+
// toBlob è un'operazione asincrona, verrà invocata la funzione di callback al termine
190191
canvas.toBlob(function(blob) {
191-
// blob ready, download it
192+
// il blob è pronto, lo scarichiamo
192193
let link = document.createElement('a');
193194
link.download = 'example.png';
194195

195196
link.href = URL.createObjectURL(blob);
196197
link.click();
197198

198-
// delete the internal blob reference, to let the browser clear memory from it
199+
// cancelliamo il riferimento interno al blob, per consentire al browser di rimuoverlo dalla memoria
199200
URL.revokeObjectURL(link.href);
200201
}, 'image/png');
201202
```
202203

203-
If we prefer `async/await` instead of callbacks:
204+
Se preferiamo, possiamo utilizzare `async/await` al posto delle callback:
204205
```js
205206
let blob = await new Promise(resolve => canvasElem.toBlob(resolve, 'image/png'));
206207
```
207208

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.
209+
Per effettuare lo screenshot di una pagina, possiamo utilizzare una libreria come <https://github.com/niklasvh/html2canvas>. Ciò che fa è semplicemente attraversare la pagina e disegnarla su un `<canvas>`. Successivamente possiamo ottenere un `Blob`, come descritto sopra.
209210

210-
## From Blob to ArrayBuffer
211+
## Da Blob a ArrayBuffer
211212

212-
The `Blob` constructor allows to create a blob from almost anything, including any `BufferSource`.
213+
Il costruttore del `Blob` consente di creare un `Blob` per qualsiasi cosa, inclusi i `BufferSource`.
213214

214-
But if we need to perform low-level processing, we can get the lowest-level `ArrayBuffer` from it using `FileReader`:
215+
Se abbiamo bisogno di eseguire operazioni di basso livello, possiamo ottenere il livello più basso, un `ArrayBuffer`, utilizzando `FileReader`:
215216

216217
```js
217-
// get arrayBuffer from blob
218+
// otteniamo arrayBuffer da un blob
218219
let fileReader = new FileReader();
219220

220221
*!*
@@ -227,15 +228,15 @@ fileReader.onload = function(event) {
227228
```
228229

229230

230-
## Summary
231+
## Riepilogo
231232

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".
233+
Mentre `ArrayBuffer`, `Uint8Array` e gli altri `BufferSource` sono "dati binari", un [Blob](https://www.w3.org/TR/FileAPI/#dfn-Blob) rappresenta "un dato binario con tipo".
233234

234-
That makes Blobs convenient for upload/download operations, that are so common in the browser.
235+
Questo rende i `Blob` convenienti per le operazioni di upload/download, che sono piuttosto comuni nei browser.
235236

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.
237+
I metodi che eseguono richieste web, come [XMLHttpRequest](info:xmlhttprequest), [fetch](info:fetch) e così via, sono in grado di operare con i `Blob` nativamente, come con tutti gli altri tipi di dato binari.
237238

238-
We can easily convert between `Blob` and low-level binary data types:
239+
Possiamo convertire molto rapidamente da `Blob` a dati binari a basso livello:
239240

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.
241+
- Possiamo creare un `Blob` da un `TypedArray` utilizzando il costruttore `new Blob(...)`.
242+
- Possiamo ricostruire un `ArrayBuffer` da un `Blob` utilizzando `FileReader`, e successivamente creare un visualizzatore per visualizzare ed elaborare i dati binari a basso livello.

0 commit comments

Comments
 (0)