I recently ran into the JavaScript Blob object, I used it to initialize a web worker where the code was contained within a script tag in the document.
Based on the MDN documentation:
A Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn’t necessarily in a JavaScript-native format.
Why is the object needed/useful?
asked Mar 14, 2015 at 23:43
8 gold badges38 silver badges63 bronze badges
Basically, Blob gives JavaScript something like temporary files, and URL.createObjectURL() lets you treat those blobs as though they were files on a web server.
10 gold badges74 silver badges104 bronze badges
answered Jan 20, 2019 at 23:38
You may need to send through an API where a URL is expecting data that is file-like.
Blobs allow you to construct file like objects on the client that you can pass to apis that expect urls instead of requiring the server provides the file.
See more here.
answered Mar 14, 2015 at 23:46
1 gold badge7 silver badges21 bronze badges
Конструктор Blob() возвращает новый объект Blob. Содержимое blob состоит из объединённых значений, переданных в параметре array.
- Синтаксис
- Параметры
- See also
- Using blobs
- Constructor
- Instance properties
- Instance methods
- Examples
- Creating a URL representing the contents of a typed array
- JavaScript
- Result
- Specifications
- Использование Blob
- Конструктор
- Свойства
- Методы
- Примеры
- Создание URL для содержимого типизированного массива
- HTML
- Другой пример
- Извлечение данных из Blob
- Downloading data from the internet as a blob
- Example loading a file from local disk on the page and getting the
- Uploading a blob
- Reading from the blob
Синтаксис
var aBlob = new Blob( array, options );
Параметры
BCD tables only load in the browser
See also
ffmpeg -i «http://example.com/video_url.m3u8» -c copy -bsf:a aac_adtstoasc «output.mp4»
output.mp4 — будет ваше видео) имя файла в команде можно менять 😉
создайте на той же странице такой элемент через инструменты разработчика и нажмите на эту ссылку, атрибут download отменяет переход по ссылке и выдает файл на скачивание, а его свойство, то есть ‘filename’ это имя сохраняемого файла
Может это конечно совсем не по-гиковски, но чем пробовать качать блобы (они кстати насколько я помню разбиты на несколько кусков), я бы просто зашел на ru.savefrom.net и вставил туда ссылочку на видео (если это youtube, vimeo, daylimotion и др. популярные сервисы). Это просто быстрее и удобнее
колдовства html5 с блобами нет в internet explorer
Выше комментировали про этот способ но ненаписали подробностей. Описываю процесс более подробно: Открыл исходный код, нашел там ссылку типа
Так что скорее всего имея такую ссылку можно воспользоваться решениями от savefromnet. А еще я интереса ради просмотрел что там в этом blob и там нашлось куча ссылок на TS файлы (порядка 170) и на M3U8 несколько ссылок, которые не открывались в VLC. копать дальше не стал, так как цель исследования была в другом.
через инструменты разработчика попробуй
Find out what is a Blob and how to use it
Web Browsers implement a Blob object, which is responsible for holding data.
Blob means “Binary Large Object” and it’s an opaque representation of a chunk of bytes.
Blobs are used for many things.
They can be created from content from the network. They can be saved to disk, or read from a disk. They are the underlying data structure for File used in the FileReader API, for example.
A blob can be sent between Web Workers and iFrames using the Channel Messaging API, and from a server to a client using the Push API.
Blobs can also be referenced using URLs.
You can extract text (or bytes) stored in a blob, and blobs can even be stored directly in IndexedDB, and they can be retrieved from there, too.
See my IndexedDB tutorial
Blobs are a fundamental data type to understand.
A blob can be created:
The constructor takes an array of values. Even if you have just one string to put in the blob, you must wrap it in an array.
You are not required to put a String value. You can pass:
The Blob constructor takes an optional second parameter, which represents the MIME type:
Once you have a Blob object, you can access its 2 properties:
and you can call its only methods, slice().
When you call slice() you can retrieve a part of the blob.
This is an example of creating a new blob from bytes 10 to 20 of aBlob:
Blob URLs (ref W3C, official name) or Object-URLs (ref. M DN and method name) are used with a Blob or a File object.
I opened the blob URL that was in src of the video, but it gave an error. I can’t open the link, but it was working with the src tag. How is this possible?
Blob URLs can only be generated internally by the browser. U RL.createObjectURL() will create a special reference to the Blob or File object which later can be released using URL.revokeObjectURL(). These URLs can only be used locally in the single instance of the browser and in the same session (ie. the life of the page/document).
What is a blob URL? Why it is used?
Blob URL/Object URL is a pseudo protocol to allow Blob and File objects to be used as URL source for things like images, download links for binary data and so forth.
For example, you can not hand an Image object raw byte-data as it would not know what to do with it. It requires for example images (which are binary data) to be loaded via URLs. This applies to anything that require an URL as source. Instead of uploading the binary data, then serve it back via an URL it is better to use an extra local step to be able to access the data directly without going via a server.
It is also a better alternative to Data-URI which are strings encoded as Base-64. The problem with Data-URI is that each char takes two bytes in JavaScript. On top of that a 33% is added due to the Base-64 encoding. Blobs are pure binary byte-arrays which does not have any significant overhead as Data-URI does, which makes them faster and smaller to handle.
Can I make my own blob URL on a server?
No, Blob URLs/Object URLs can only be made internally in the browser. You can make Blobs and get File object via the File Reader API, although BLOB just means Binary Large OBject and is stored as byte-arrays. A client can request the data to be sent as either ArrayBuffer or as a Blob. The server should send the data as pure binary data. Databases often uses Blob to describe binary objects as well, and in essence we are talking basically about byte-arrays.
Any additional details about blob URLs would be helpful as well.
You need to encapsulate the binary data as a BLOB object, then use URL.createObjectURL() to generate a local URL for it:
URL-адреса Blob (ref W3C , официальное имя) или Object-URLs (ссылка MDN и имя метода) используются с объектом Blob или File .
src = «blob: https: //crap.crap » Я открыл url blob, который был в src видео, он дал ошибку, и я не могу открыть, но работал с тегом src, как это возможно?
URL-адреса Blob могут генерироваться только браузером. URL.createObjectURL() создаст специальную ссылку на объект Blob или File, который позже может быть выпущен с помощью URL.revokeObjectURL() . Эти URL-адреса могут использоваться только локально в одном экземпляре браузера и в том же сеансе (т. Е. В жизни страницы / документа).
Что такое URL-адрес blob? Почему он используется?
URL-адрес Blob URL / Object – псевдопротокол, позволяющий использовать объекты Blob и File в качестве источника URL-адреса для таких вещей, как изображения, ссылки для загрузки для двоичных данных и т. Д.
Например, вы не можете передать исходные байтовые данные объекта Image, поскольку он не знал, что с ним делать. Для загрузки URL-адресов требуется, например, изображения (которые являются двоичными данными). Это относится ко всему, что требует URL-адреса в качестве источника. Вместо того, чтобы загружать двоичные данные, затем отсылайте их обратно через URL-адрес, лучше использовать дополнительный локальный шаг, чтобы иметь возможность напрямую обращаться к данным, не проходя через сервер.
Это также лучшая альтернатива Data-URI, которые являются строками, закодированными как Base-64 . Проблема с Data-URI заключается в том, что каждый символ принимает два байта в JavaScript. Кроме того, из-за кодировки Base-64 добавляется 33%. Blobs – это чистые двоичные байт-массивы, которые не имеют значительных служебных данных, как Data-URI, что делает их более быстрыми и меньшими для обработки.
Могу ли я создать свой собственный код blob на сервере?
Нет, URL-адреса Blob / URL-адреса объектов могут быть сделаны только внутри браузера. Вы можете сделать Blobs и получить объект File через API чтения файлов, хотя BLOB просто означает Binary Large OBject и хранится в виде байтовых массивов. Клиент может запросить отправку данных как ArrayBuffer или как Blob. Сервер должен отправлять данные как чистые двоичные данные. Базы данных часто используют Blob для описания двоичных объектов, и в основном мы говорим в основном о байтовых массивах.
если у вас есть дополнительная информация
Вам необходимо инкапсулировать двоичные данные как объект BLOB, а затем использовать URL.createObjectURL() для создания локального URL-адреса для него:
Обратите внимание, что URL может быть префикс в webkit-браузерах, поэтому используйте:
The Blob object represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a ReadableStream so its methods can be used for processing the data.
Using blobs
The APIs accepting Blob objects are also listed in the File documentation.
Constructor
Returns a newly created Blob object which contains a concatenation of all of the data in the array passed into the constructor.
Instance properties
The size, in bytes, of the data contained in the Blob object.
A string indicating the MIME type of the data contained in the Blob. If the type is unknown, this string is empty.
Instance methods
Returns a promise that resolves with an ArrayBuffer containing the entire contents of the Blob as binary data.
Returns a new Blob object containing the data in the specified range of bytes of the blob on which it’s called.
Returns a ReadableStream that can be used to read the contents of the Blob.
Returns a promise that resolves with a string containing the entire contents of the Blob interpreted as UTF-8 text.
Examples
The Blob() constructor can create blobs from other objects. For example, to construct a blob from a JSON string:
obj
blob obj
Creating a URL representing the contents of a typed array
This example creates a typed array containing the ASCII codes for the space
character through the letter Z, then converts it to an object URL. A link to
open that object URL is created. Click the link to see the decoded object URL.
JavaScript
windowself windowtop
// to first open it in its own tab or window. Otherwise, this
// example won’t work.
p document
ptextContent
button document
buttontextContent «View live result of the example code above»
pbutton
button windowlocationhref
typedArraybuffer mimeType
bytes
i i i
bytesi i
url bytes
link document
linkhref url
linkinnerText «Open the array URL»
documentbodylink
Result
reader
reader
// reader.result contains the contents of blob as a typed array
readerblob
text blob
Or by using Blob.prototype.text():
text 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
Объект Blob представляет из себя подобный файлу объект с неизменяемыми, необработанными данными; они могут читаться как текст или двоичные данные, либо могут быть преобразованы в ReadableStream (en-US), таким образом, его методы могут быть использованы для обработки данных.
Blob-ы могут представлять данные, которые не обязательно должны быть в родном для JavaScript формате. Интерфейс File основан на Blob, наследует функциональность Blob и расширяет его для поддержки файлов на стороне пользователя.
Использование Blob
Для создания Blob не из объектов и данных blob, используйте конструктор Blob() . Чтобы создать blob из подмножества данных из другого blob, используйте метод slice(). Чтобы получить объект Blob для файла на файловой системе пользователя, смотрите документацию на File.
API, принимающие объекты Blob, также перечислены в документации на File.
Примечание: Метод slice() имеет изначально задаваемую длину как второй аргумент, что используется для указания числа байт копируемых в новый Blob. Если указать такие параметры start + length, которые превышают размер исходного Blob, то возвращаемый Blob будет содержать данные от начального индекса (start index) до конца исходного Blob.
Примечание: Следует помнить ,что метод slice() имеет сторонние префиксы в некоторых браузерах: blob.mozSlice() для Firefox 12 и ранее, так же blob.webkitSlice() в Safari. Старая версия метода slice(), без сторонних приставок, имеет другой алгоритм и устарела. Поддержка blob.mozSlice() была убрана в Firefox 30.
Конструктор
Возвращает создаваемый объект Blob, который содержит соединение всех данных в массиве, переданном в конструктор.
Свойства
Blob.isClosed Только для чтения
Логическое значение, показывающее, вызывался ли метод Blob.close() у blob. Закрытый blob не может быть прочитан.
Blob.size (en-US) Только для чтения
Размер данных, содержащихся в объекте Blob, в байтах.
Blob.type (en-US) Только для чтения
Строка с MIME-типом данных, содержащихся в Blob. Если тип неизвестен, строка пуста.
Методы
Закрывает Blob объект, по возможности освобождая занятые им ресурсы.
Возвращает новый Blob объект, содержащий данные в указанном диапазоне байтов исходного Blob.
Возвращает ReadableStream (en-US), который может использоваться для чтения содержимого Blob.
Возвращает promise, который исполняется с USVString, содержащей всё содержимое Blob, интерпретируемое как текст UTF-8.
Примеры
Конструктор Blob() constructor может создавать объекты blob из других объектов. Например, чтобы сконструировать blob из строки JSON:
Предупреждение: До того как конструктор Blob стал доступен, это могло быть выполнено через устаревший API BlobBuilder (en-US):
Создание URL для содержимого типизированного массива
Следующий код создаёт типизированный массив JavaScript и создаёт новый Blob, содержащий данные типизированного массива. Затем вызывается URL.createObjectURL() для преобразования blob в URL.
HTML
typedArraybuffer mimeType
bytes
i i i
bytesi i
url bytes
link document
linkhref url
linkinnerText «Open the array URL»
documentbodylink
Другой пример
typedArray
blob typedArray // pass a useful mime type here
url 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.
Извлечение данных из Blob
Один из способов прочесть содержимое Blob – это использовать FileReader. Следующий код читает содержимое Blob как типизированный массив.
Другой способ прочитать содержимое из Blob – это использовать Response. Следующий код читает содержимое Blob как текст:
Или можно использовать Blob.text() (en-US):
Используя другие методы FileReader, возможно прочесть содержимое объекта Blob как строку или как URL.
I mentioned that blobs can also be referenced using URLs.
Blob URLs are generated by the browser and are internal references. Given a blob, you can generate a URL to it using the URL.createObjectURL() function.
A Blob URL starts with the blob:// scheme.
Once the browser sees that URL, it will serve the corresponding blob stored in memory or in the disk.
Blob URLs are different from Data URLs (starting with data:), because they don’t store the data in the URL. They are also different from File URLs (starting with file:), since they do not reveal sensitive information like the file path.
If you access a Blob URL that is no longer existing, you will get a 404 error from the browser.
Once you generate a blob URL, you can remove it calling the URL.revokeObjectURL() and passing the URL.
Downloading data from the internet as a blob
We can download data from the internet and store it into a Blob object using this syntax:
Example loading a file from local disk on the page and getting the
In this sample code we have an input element to select an image. Once an image is selected, we remove the input element and we display the image. We also clear the blob once we are done displaying the image:
Uploading a blob
This code is used as a callback to an input type or drag and drop. We load a blob to a url using XHR, using an f function to track progress:
Reading from the blob
You can’t directly access the data contained in the blob.
To be able to do so, we must use a FileReader object.




