Este artigo necessita de uma revisão editorial. Como posso ajudar.
Esta tradução está incompleta. Ajude atraduzir este artigo.
Summary
Um Blob object representa um objeto, do tipo arquivo, com dados brutos imutáveis. Blobs representam dados que não estão necessáriamente em formatos padrões do JavaScript. A interface File é baseada no Bloob, herdando blob funcionalmente e expandindo ele para dar suporte aos arquivos do sistema do usuário.
Um jeito fácil de construir um Blob é invocando o construtor Blob(). Outro jeito é usando a função slice() para criar um blob que contém um subset de outros dados de Bloob.
Construtor
Blob()- Retorna um novo
Blobobject cujo conteúdo é construido pela concatenação do array de valores passado pelo parâmentro.
Propriedades
Blob.isClosedSomente leitura- Um valor boolean, indicando se o
Blob.close()método foi chamado no blob. Blobs fechados não podem ser lidos.
Blob.sizeSomente leitura- Tamanho em bytes dos dados contidos no Blob Object.
Blob.typeSomente leitura- Uma string que indica o MIME type dos dados no Blob. Se o tipo é desconhecido, então retorna uma vazia.
Métodos
Blob.close()- Fecha o blob, possivelmente liberando recursos subjacentes.
Blob.slice()- Retorna um novo
Blobobject contendo os dados de uma específica quantidade de bytes do Blob.
slice() tem prefixos de fornecedores em alguns browsers e versões: blob.mozSlice() para o Firefox 12 e anteriores e blob.webkitSlice() no Safari. Uma versões antiga do método slice(), sem prefixos de fornecedores, teve diferentes semânticas, e é obsoleto. O suporte para blob.mozSlice() foi removido no Firefox 30.Exemplos
Exemplos de Uso do Construtor Blob
O código à seguir:
var aFileParts = ['<a id="a"><b id="b">hey!</b></a>'];
var oMyBlob = new Blob(aFileParts, {type : 'text/html'}); // the blob
equivale a:
var oBuilder = new BlobBuilder();
var aFileParts = ['<a id="a"><b id="b">hey!</b></a>'];
oBuilder.append(aFileParts[0]);
var oMyBlob = oBuilder.getBlob('text/xml'); // the blob
O BlobBuilder oferece outra maneira para criar Blobs, mas é depreciado e não deveria mais ser usado.
Example for creating a URL to a typed array using a blob
O código à seguir:
var typedArray = GetTheTypedArraySomehow();
var blob = new Blob([typedArray], {type: 'application/octet-binary'}); // pass a useful mime type here
var url = URL.createObjectURL(blob);
// url will be something like: blob:d3958f5c-0777-0845-9dcf-2cb28783acaf
// now you can use the url in any context that regular URLs can be used in, for example img.src, etc.
Exemplo de Extração de Dados de Um Blob
O único jeito de ler o conteúdo de um Blob é usando FileReader. O código a seguir lê o conteudo de um Blob como um Array.
var reader = new FileReader();
reader.addEventListener("loadend", function() {
// reader.result contains the contents of blob as a typed array
});
reader.readAsArrayBuffer(blob);
By using other methods of FileReader, it is possible to read the contents of a Blob as a string or a data URL.
Specifications
| Specification | Status | Comment |
|---|---|---|
| File API The definition of 'Blob' in that specification. |
Working Draft | Initial definition. |
Browser compatibility
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
|---|---|---|---|---|---|
| Basic support | 5 | 4 | 10 | 11.10 | 5.1 |
slice() |
10 webkit‡ 21 |
5 moz‡ 13 |
10 | 12 | 5.1 (534.29) webkit |
Blob() constructor |
20 | 13.0 (13.0) | 10 | 12.10 | 6 (536.10) |
| Feature | Android | Firefox Mobile (Gecko) | IE Phone | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|
| Basic support | ? | 13.0 (13.0) | ? | ? | ? |
Notes on the slice() implementations
The slice() method had initially taken length as the second argument to indicate the number of bytes to copy into the new Blob. If you specified values such that start + length exceeded the size of the source Blob, the returned Blob contained data from the start index to the end of the source Blob.
That version of the slice() was implemented in Firefox 4, WebKit, and Opera 11.10. However, since that syntax is differed from Array.slice() and String.slice(), Gecko and WebKit removed support and added support for the new syntax as mozSlice()/Blob.webkitSlice.
Starting in Gecko 13.0 (Firefox 13.0 / Thunderbird 13.0 / SeaMonkey 2.10) and Chrome 21, slice() is no longer prefixed. The support for mozSlice() has been dropped with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27).‡
Gecko notes
Prior to Gecko 12.0 (Firefox 12.0 / Thunderbird 12.0 / SeaMonkey 2.9), there was a bug that affected the behavior of slice(); it did not work for start and end positions outside the range of signed 64-bit values; it has now been fixed to support unsigned 64-bit values.
Chrome Code - Scope Availability
In the JSM scope Blob is available without needing to do anything special.
In Bootstrap scope, this must be imported in like so:
const {Blob, Services} = Cu.import('resource://gre/modules/Services.jsm', {});