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
`ArrayBuffer`and views are a part of ECMA standard, a part of JavaScript.
3
+
`ArrayBuffer`et les vues font partie de la norme ECMA, une partie de JavaScript.
4
4
5
-
In the browser, there are additional higher-level objects, described in[File API](https://www.w3.org/TR/FileAPI/), in particular`Blob`.
5
+
Dans le navigateur, il existe d'autres objets de niveau supérieur, décrits dans[File API](https://www.w3.org/TR/FileAPI/), en particulier`Blob`.
6
6
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`consiste en une chaîne de caractères optionnelle `type` (un type de MIME habituellement), plus `blobParts` -- une séquence d'autres objets`Blob`, chaînes de caractères et`BufferSource`.
8
8
9
9

10
10
11
-
The constructor syntax is:
11
+
La syntaxe du constructeur est la suivante:
12
12
13
13
```js
14
14
newBlob(blobParts, options);
15
15
```
16
16
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`**est un tableau de`Blob`/`BufferSource`/`String`.
18
+
-**`options`**objet optionnel:
19
+
-**`type`** -- le type du `Blob`, généralement de type MIME, par exemple. `image/png`,
20
+
-**`endings`** -- s'il faut transformer la fin de ligne pour rendre le `Blob`correspondent aux nouvelles lignes de l'OS actuel (`\r\n`ou`\n`). `"transparent"`Par défaut (ne fait rien), mais peut aussi être`"native"` (transformer).
21
21
22
-
For example:
22
+
Par exemple:
23
23
24
24
```js
25
-
//create Blob from a string
25
+
//créer un Blob à partir d'une chaîne
26
26
let blob =newBlob(["<html>…</html>"], {type:'text/html'});
27
-
//please note: the first argument must be an array [...]
27
+
//veuillez noter: le premier argument doit être un tableau [...]
28
28
```
29
29
30
30
```js
31
-
//create Blob from a typed array and strings
32
-
let hello =newUint8Array([72, 101, 108, 108, 111]); // "Hello" in binary form
31
+
//créer un objet blob à partir d'un tableau typés et de chaînes de caractères
32
+
let hello =newUint8Array([72, 101, 108, 108, 111]); // "Hello" sous forme binaire
33
33
34
34
let blob =newBlob([hello, '', 'world'], {type:'text/plain'});
-**`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`** -- l'octet de départ, par défaut 0.
45
+
-**`byteEnd`** -- le dernier octet (exclusif, par défaut jusqu'à la fin).
46
+
-**`contentType`** -- Le`type`du nouvel objet blob, par défaut le même que la source.
47
47
48
-
The arguments are similar to`array.slice`, negative numbers are allowed too.
48
+
Les arguments sont similaires à`array.slice`, les nombres négatifs sont également autorisés.
49
49
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="Les objets `Blob`sont immuables"
51
+
Nous ne pouvons pas modifier les données directement dans un `Blob`, mais nous pouvons découper des parties d'un`Blob`, créer de nouveaux objets `Blob`à partir d'eux, les mélanger dans un nouveau`Blob`et ainsi de suite.
52
52
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
+
Ce comportement est similaire aux chaînes de caractères JavaScript: nous ne pouvons pas changer un caractère dans une chaîne, mais nous pouvons créer une nouvelle chaîne corrigée.
54
54
```
55
55
56
-
## Blob as URL
56
+
## Blob comme URL
57
57
58
-
A Blob can be easily used as an URL for `<a>`, `<img>` or other tags, to show its contents.
58
+
Un Blob peut être facilement utilisé comme URL pour `<a>`, `<img>` ou d'autres balises, pour afficher son contenu.
59
59
60
-
Thanks to `type`, we can also download/upload `Blob` objects, and the `type` naturally becomes `Content-Type` in network requests.
60
+
Grâce au `type`, nous pouvons également télécharger / uploader des objets `Blob`, et le `type` devient naturellement `Content-Type` dans les requêtes réseau.
61
61
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
+
Commençons par un exemple simple. En cliquant sur un lien, vous téléchargez un `Blob` généré dynamiquement avec le contenu de `hello world` sous forme de fichier:
63
63
64
64
```html run
65
-
<!-- download attribute forces the browser to download instead of navigating -->
65
+
<!-- l'attribut de téléchargement force le navigateur à télécharger au lieu de naviguer -->
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
+
Le navigateur stocke un mappage URL -> `Blob` en interne pour chaque URL générée par `URL.createObjectURL`. Donc, ces URL sont courtes, mais permettent d'accéder au`Blob`.
101
101
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
+
Une URL générée (et donc le lien avec elle) n'est valide que dans le document actuel, tant qu'il est ouvert. Et cela permet de référencer le`Blob`dans`<img>`,`<a>`, ou tout autre objet qui attend une URL.
103
103
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
+
Il y a cependant un effet secondaire. Bien qu'il y ait un mappage pour un `Blob`, le`Blob`lui-même réside dans la mémoire. Le navigateur ne peut pas le libérer.
105
105
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
+
Le mappage est automatiquement effacé lors du déchargement du document, les objets `Blob`sont alors libérés. Mais si une application dure longtemps, cela ne se produit pas de sitôt.
107
107
108
-
**So if we create a URL, that`Blob`will hang in memory, even if not needed any more.**
108
+
**Donc, si nous créons une URL, ce`Blob`restera en mémoire, même s'il n'est plus nécessaire.**
109
109
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)`supprime la référence du mappage interne, permettant ainsi de supprimer le `Blob`(s'il n'y a pas d'autres références), et de libérer la mémoire.
111
111
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
+
Dans le dernier exemple, nous voulons que le `Blob`ne soit utilisé qu'une seule fois, pour un téléchargement instantané, donc nous appelons`URL.revokeObjectURL(link.href)`immédiatement.
113
113
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
+
Dans l'exemple précédent avec le lien HTML cliquable, nous n'appelons pas`URL.revokeObjectURL(link.href)`, car cela rendrait l'url `Blob`invalide. Après la révocation, comme le mappage est supprimé, l'URL ne fonctionne plus.
115
115
116
-
## Blob to base64
116
+
## Blob en base64
117
117
118
-
An alternative to`URL.createObjectURL`is to convert a`Blob`into a base64-encoded string.
118
+
Une alternative à`URL.createObjectURL`est de convertir un`Blob`en une chaîne de caractères encodée en base64.
119
119
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
+
Cet encodage représente des données binaires sous la forme d'une chaîne de caractères "lisibles" ultra-sûrs avec des codes ASCII de 0 à 64. Et ce qui est plus important - nous pouvons utiliser cet encodage dans "data-urls".
121
121
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
+
Une [URL de données](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs)a la forme`data:[<mediatype>][;base64],<data>`. Nous pouvons utiliser de telles URL partout, au même titre que les URL "ordinaires".
The browser will decode the string and show the image: <imgsrc="data:image/png;base64,R0lGODlhDAAMAKIFAF5LAP/zxAAAANyuAP/gaP///wAAAAAAACH5BAEAAAUALAAAAAAMAAwAAAMlWLPcGjDKFYi9lxKBOaGcF35DhWHamZUW0K4mAbiwWtuf0uxFAgA7">
130
+
Le navigateur décodera la chaîne de caractères et affichera l'image: <imgsrc="data:image/png;base64,R0lGODlhDAAMAKIFAF5LAP/zxAAAANyuAP/gaP///wAAAAAAACH5BAEAAAUALAAAAAAMAAwAAAMlWLPcGjDKFYi9lxKBOaGcF35DhWHamZUW0K4mAbiwWtuf0uxFAgA7">
131
131
132
132
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
+
Pour transformer un`Blob`en base64, nous utiliserons l'objet `FileReader`intégré. Il peut lire les données des Blobs dans plusieurs formats. Dans le [chapitre suivant](info:file)nous le couvrirons plus en détail.
134
134
135
-
Here's the demo of downloading a blob, now via base-64:
135
+
Voici la démo du téléchargement d'un blob, maintenant via base-64:
136
136
137
137
```js run
138
138
let link =document.createElement('a');
@@ -142,79 +142,79 @@ let blob = new Blob(['Hello, world!'], {type: 'text/plain'});
142
142
143
143
*!*
144
144
let reader =newFileReader();
145
-
reader.readAsDataURL(blob); //converts the blob to base64 and calls onload
145
+
reader.readAsDataURL(blob); //convertit le blob en base64 et appelle onload
146
146
*/!*
147
147
148
148
reader.onload=function() {
149
-
link.href=reader.result; //data url
149
+
link.href=reader.result; //URL de données
150
150
link.click();
151
151
};
152
152
```
153
153
154
-
Both ways of making an URL of a `Blob`are usable. But usually`URL.createObjectURL(blob)`is simpler and faster.
154
+
Les deux manières de créer une URL d'un `Blob`sont utilisables. Mais généralement`URL.createObjectURL(blob)`est plus simple et plus rapide.
155
155
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 vers l'URL de données"
157
+
+ Nous devons les révoquer si nous nous soucions de la mémoire.
158
+
+ Accès direct au blob, pas d'"encodage / décodage"
159
+
- Pas besoin de révoquer quoi que ce soit.
160
+
- Perte de performances et de mémoire sur les gros objets `Blob` pour l'encodage.
161
161
```
162
162
163
-
## Image to blob
163
+
## Image à blob
164
164
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
+
Nous pouvons créer un`Blob`d'une image, une partie d'image, ou même faire une capture d'écran de page. C'est pratique pour le télécharger quelque part.
166
166
167
-
Image operations are done via `<canvas>` element:
167
+
Les opérations sur les images se font via l'élément `<canvas>`:
168
168
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.Dessinez une image (ou sa partie) sur le canevas en utilisant[canvas.drawImage](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage).
170
+
2.Appeler la méthode canvas [.toBlob(callback, format, quality)](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)qui crée un`Blob`et exécute`callback`avec lui une fois terminé.
171
171
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
+
Dans l'exemple ci-dessous, une image est simplement copiée, mais nous pourrions la couper ou la transformer sur un canevas avant de créer un blob:
173
173
174
174
```js run
175
-
//take any image
175
+
//prendre n'importe quelle image
176
176
let img =document.querySelector('img');
177
177
178
-
//make <canvas> of the same size
178
+
//rendre <canvas> de la même taille
179
179
let canvas =document.createElement('canvas');
180
180
canvas.width=img.clientWidth;
181
181
canvas.height=img.clientHeight;
182
182
183
183
let context =canvas.getContext('2d');
184
184
185
-
//copy image to it (this method allows to cut image)
185
+
//copier l'image dessus (cette méthode permet de couper l'image)
186
186
context.drawImage(img, 0, 0);
187
-
//we can context.rotate(), and do many other things on canvas
187
+
//nous pouvons context.rotate(), et faire beaucoup d'autres choses sur canvas
188
188
189
-
// toBlob is async opereation, callback is called when done
189
+
// toBlob est une opération asynchrone, le rappel est appelé une fois terminé
190
190
canvas.toBlob(function(blob) {
191
-
// blob ready, download it
191
+
// blob prêt, téléchargez-le
192
192
let link =document.createElement('a');
193
193
link.download='example.png';
194
194
195
195
link.href=URL.createObjectURL(blob);
196
196
link.click();
197
197
198
-
//delete the internal blob reference, to let the browser clear memory from it
198
+
//supprimer la référence blob interne, pour laisser le navigateur en effacer la mémoire
199
199
URL.revokeObjectURL(link.href);
200
200
}, 'image/png');
201
201
```
202
202
203
-
If we prefer`async/await`instead of callbacks:
203
+
Si nous préférons`async/await`au lieu de callbacks:
204
204
```js
205
205
let blob =awaitnewPromise(resolve=>canvasElem.toBlob(resolve, 'image/png'));
206
206
```
207
207
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
+
Pour faire une capture d'écran d'une page, nous pouvons utiliser une bibliothèque telle que<https://github.com/niklasvh/html2canvas>. Ce qu'elle fait, c'est simplement parcourir la page et la dessiner sur un `<canvas>`. Ensuite, nous pouvons en obtenir un `Blob`de la même manière que ci-dessus.
209
209
210
-
## From Blob to ArrayBuffer
210
+
## De Blob à ArrayBuffer
211
211
212
-
The `Blob`constructor allows to create a blob from almost anything, including any`BufferSource`.
212
+
Le constructeur `Blob`permet de créer un blob à partir de presque tout, y compris de n'importe quel`BufferSource`.
213
213
214
-
But if we need to perform low-level processing, we can get the lowest-level `ArrayBuffer`from it using`FileReader`:
214
+
Mais si nous devons effectuer un traitement de bas niveau, nous pouvons obtenir des `ArrayBuffer`de plus bas niveau en utilisant`FileReader`:
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
+
Alors qu'`ArrayBuffer`, `Uint8Array`et autres`BufferSource`sont des "données binaires", un[Blob](https://www.w3.org/TR/FileAPI/#dfn-Blob) représente des "données binaires de type".
233
233
234
-
That makes Blobs convenient for upload/download operations, that are so common in the browser.
234
+
Cela rend les Blobs pratiques pour les opérations de téléchargement (upload / download), qui sont courantes dans le navigateur.
235
235
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
+
Les méthodes qui effectuent des requêtes Web, telles que[XMLHttpRequest](info:xmlhttprequest), [fetch](info:fetch)et ainsi de suite, peuvent fonctionner avec`Blob`de manière native, ainsi qu'avec d'autres types binaires.
237
237
238
-
We can easily convert betweeen `Blob`and low-level binary data types:
238
+
Nous pouvons facilement convertir les types de données binaires `Blob`et de bas niveau:
239
239
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
+
-Nous pouvons créer un Blob à partir d'un tableau typé en utilisant le constructeur `new Blob(...)`.
241
+
-Nous pouvons récupérer un`ArrayBuffer`à partir d'un Blob en utilisant `FileReader`, puis créer une vue dessus pour un traitement binaire de bas niveau.
0 commit comments