What is a blob URL and why it is used?
Asked Answered
G

6

661

I am having trouble with blob URLs.

I was searching for src of a video tag on YouTube and I found that the video src was like:

src="blob:https://video_url"

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?

I have a few questions:

  • What is a blob URL?
  • Why it is used?
  • Can I make my own blob URL on a server?

Any additional details about blob URLs would be helpful as well.

Gabby answered 16/6, 2015 at 10:9 Comment(3)
Also https://mcmap.net/q/64932/-convert-blob-url-to-normal-url/632951Ventose
Essentially disallows hotlinking. (like youtube)Baker
Suggesting that its purpose is to "disallow hotlinking" is bit disingenuous. Rather, it allows the creation of ephemeral content within the browser itself. If ephemeral content is derived from some downloaded content, such as with Youtube, then you're still welcome to hotlink that source directly, but it might take you a bit of effort of with a JS debugger to find it. (Of course, if you then use that URL to download a non-transient copy, THAT may not be permitted by your access licence, nor by your rights under copyright law.)Logistician
P
638

Blob URLs (ref W3C, official name) or Object-URLs (ref. MDN 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. URL.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:

var blob = new Blob([arrayBufferWithPNG], {type: "image/png"}),
    url = URL.createObjectURL(blob),
    img = new Image();

img.onload = function() {
    URL.revokeObjectURL(this.src);     // clean-up memory
    document.body.appendChild(this);   // add image to DOM
}

img.src = url;                         // can now "stream" the bytes
Poultry answered 17/6, 2015 at 2:38 Comment(17)
I have a php script that streams a video by id that is $_GET["id"] so how I can give a url like blob:// so it can be used by my video src like youtube is using.Where ever i look is only javascript....Let me give you some information about url i have url like website.com/video.php?id=ljduwkbcj27dj so how to use javascript or php to give a blob urlGabby
@Waqas if the URL goes to a video file online (or a page pushing a video file) you can set that URL directly as source for the video element (ie. video.src = "http://website.com/video.php?id=ljduwkbcj27dj";). This is more related to the response header from the server, and what type of data the page sends back. But this would be a bit out of scope of the original question to cover. Object-URLs are only used locally as a bridge between binary data and elements requiring URL as source.Poultry
so why youtube uses blobGabby
@K3N Is it possible to convert that object url to dataUri ?Aideaidedecamp
Re "there is nothing called Blob URL"; That's the name it's referred by: "The Blob URL".Ventose
@Ventose seem to float conflicting versions of the name. But fair enough, the W3C is the official source so I'll update (but I'll predict we'll get stuck with the method name, ie. createObjectURL() though).Poultry
@K3N is it possible to get the true source of the blob URL instead of the generated URL? Nest cam generates a blob URL to prevent people from recording their own camerasLeonardaleonardi
enlightenment for me "BLOB just means Binary Large OBject"Jehias
The last line would throw if URL is not defined, should be (window.URL || window.webkitURL).And this answers missed the very special case of the question: blobURL can also point to other objects than Blobs e.g MediaSource (like for YT) or MediaStream (even though it's being deprecated)Sices
How do I block the domain that created the blob content?Johannesburg
Is it possible to retrieve the contents of the blob/file object and download whatever it is (image or video)?Superintendency
In the OPs original context, why would a YouTube embed player use a blob: URL? I assume the browser downloads the video stream as binary, then creates the video element with a blob URL. How is t his better than just having the video element download the URL directly?Colophon
This might be pertinent to the people wondering how to download a blob video: https://mcmap.net/q/64933/-how-do-we-download-a-blob-url-video-closed/1530508Tuberose
@Colophon YouTube doesn't use Blobs, they use the MediaSource API, which also gets pointed to by blob:// URLs. Unfortunately this answer completely missed that point, even though it is the one being asked about in the OP.Sices
Most concise and useful explanation of the reasoning behind the Blob, File, base64, and Object URL relationship I've ever seen.Johnnajohnnie
Sorry... I need better context for this answer and question. I get these "blob:http://" URLs in MacOS "source origin extended attribute" of files - that tell me "where the file came from". I try to understand "what are blob urls" and this answer doesn't help enough in my context. BTW - the downloaded files - were NOT created locally, but really downloaded from some server.Fond
"Blob URLs can only be generated internally by the browser." - what does it mean? I don't think it's true.Felecia
O
14

This Javascript function supports to show the difference between the Blob File API and the Data API to download a JSON file in the client browser:

/**
 * Save a text as file using HTML <a> temporary element and Blob
 * @author Loreto Parisi
 */

var saveAsFile = function(fileName, fileContents) {
    if (typeof(Blob) != 'undefined') { // Alternative 1: using Blob
        var textFileAsBlob = new Blob([fileContents], {type: 'text/plain'});
        var downloadLink = document.createElement("a");
        downloadLink.download = fileName;
        if (window.webkitURL != null) {
            downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
        } else {
            downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
            downloadLink.onclick = document.body.removeChild(event.target);
            downloadLink.style.display = "none";
            document.body.appendChild(downloadLink);
        }
        downloadLink.click();
    } else { // Alternative 2: using Data
        var pp = document.createElement('a');
        pp.setAttribute('href', 'data:text/plain;charset=utf-8,' +
            encodeURIComponent(fileContents));
        pp.setAttribute('download', fileName);
        pp.onclick = document.body.removeChild(event.target);
        pp.click();
    }
} // saveAsFile

/* Example */
var jsonObject = {"name": "John", "age": 30, "car": null};
saveAsFile('out.json', JSON.stringify(jsonObject, null, 2));

The function is called like saveAsFile('out.json', jsonString);. It will create a ByteStream immediately recognized by the browser that will download the generated file directly using the File API URL.createObjectURL.

In the else, it is possible to see the same result obtained via the href element plus the Data API, but this has several limitations that the Blob API has not.

Overby answered 23/4, 2018 at 21:18 Comment(3)
Can you adapt this to save a video from a tweet?Benefactor
When I set the .href to something like downloadLink.href="blob:https://www.wmur.com/aa14dc0d-c44c-4072-b918-bff92d26b9b7" and call downloadLink.click() it gives me an error Network Error.Derron
@Derron in the case the browser supports the Blob object you will use it to store the binarized contents of the file, but this function will save it as a downloadable file anyways, but using the api createObjectURL; so there's no need to change the href, unless your aim is to do something different.Overby
O
6

The OP asks:

What is blob URL? Why is it used?

Blob is just byte sequence. Browsers recognize Blobs as byte streams. It is used to get byte stream from source. According to Mozilla's 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. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.

The OP asks:

Can i make my own blob url on a server?

Yes you can there are several ways to do so for example try http://php.net/manual/en/function.ibase-blob-echo.php

Read more here:

Outbuilding answered 16/6, 2015 at 10:22 Comment(6)
Can I get any benefit by using BLOB url?Gabby
You can read this to get your answer. Obviously there are pros and cons.Outbuilding
You are mixing Object-URLs with BLOBs. Object-URL is a pseudo protocol to allow BLOBs to be used as URI source.Poultry
There are some significant flaws with this answer. Mainly as pointed out in a previous comment some very different concepts get mixed ... and then compressed into an incomplete and incorrect answer.Galasyn
I'd assume that when asking "Can i make my own blob URL on a server?", the OP is expecting to be able to pass the URL to the browser, and have it download the blob data. You can't do that, and the PHP page you link to is about database BLOB functionality, which isn't the same thing as browser/javascript BLOBs at all.Joycejoycelin
Any binary data exceeding standard datasize formats are blobs. It's not clear to me what the difference between a generic blob and the blob in this context is. There is no difference between blob:https://blob and https://blob.Stannfield
D
6

I have modified working solution to handle both the case.. when video is uploaded and when image is uploaded .. hope it will help some.

HTML

<input type="file" id="fileInput">
<div> duration: <span id='sp'></span><div>

Javascript

var fileEl = document.querySelector("input");

fileEl.onchange = function(e) {


    var file = e.target.files[0]; // selected file

    if (!file) {
        console.log("nothing here");
        return;
    }

    console.log(file);
    console.log('file.size-' + file.size);
    console.log('file.type-' + file.type);
    console.log('file.acutalName-' + file.name);

    let start = performance.now();

    var mime = file.type, // store mime for later
        rd = new FileReader(); // create a FileReader

    if (/video/.test(mime)) {

        rd.onload = function(e) { // when file has read:


            var blob = new Blob([e.target.result], {
                    type: mime
                }), // create a blob of buffer
                url = (URL || webkitURL).createObjectURL(blob), // create o-URL of blob
                video = document.createElement("video"); // create video element
            //console.log(blob);
            video.preload = "metadata"; // preload setting

            video.addEventListener("loadedmetadata", function() { // when enough data loads
                console.log('video.duration-' + video.duration);
                console.log('video.videoHeight-' + video.videoHeight);
                console.log('video.videoWidth-' + video.videoWidth);
                //document.querySelector("div")
                //  .innerHTML = "Duration: " + video.duration + "s" + " <br>Height: " + video.videoHeight; // show duration
                (URL || webkitURL).revokeObjectURL(url); // clean up

                console.log(start - performance.now());
                // ... continue from here ...

            });
            video.src = url; // start video load
        };
    } else if (/image/.test(mime)) {
        rd.onload = function(e) {

            var blob = new Blob([e.target.result], {
                    type: mime
                }),
                url = URL.createObjectURL(blob),
                img = new Image();

            img.onload = function() {
                console.log('iamge');
                console.dir('this.height-' + this.height);
                console.dir('this.width-' + this.width);
                URL.revokeObjectURL(this.src); // clean-up memory
                console.log(start - performance.now()); // add image to DOM
            }

            img.src = url;

        };
    }

    var chunk = file.slice(0, 1024 * 1024 * 10); // .5MB
    rd.readAsArrayBuffer(chunk); // read file object

};

jsFiddle Url

https://jsfiddle.net/PratapDessai/0sp3b159/

Depopulate answered 22/6, 2018 at 20:33 Comment(3)
1. What is the purpose of indentation in your code? Everyone else uses indentation to highlight logical structure of code. 2. Your JSFiddle does nothing. I tried to upload an image and a video.Electro
@Electro — It outputs to the console various information about the file uploaded. What did you expect it to do, upload it somewhere? That's kind of hard to demonstrate. The author did a reasonable job—you have to look at the code to see what it's doing.Infantilism
How does this answer the original questions of What is blob URL? Why it is used?Mcclenon
A
1

blob urls are used for showing files that the user uploaded, but they are many other purposes, like that it could be used for secure file showing, like how it is a little difficult to get a YouTube video as a video file without downloading an extension. But, they are probably more answers. My research is mostly just me using Inspect to try to get a YouTube video and an online article.

Apollinaire answered 23/12, 2021 at 4:41 Comment(0)
G
1

Another use case of blob urls is to load resources from the server, apply hacks and then tell the browser to interpret them.

One such example would be to load template files or even scss files.

Here is the scss example:

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.11.1/sass.sync.min.js"></script>
function loadCSS(text) {
    const head = document.getElementsByTagName('head')[0]
    const style = document.createElement('link')
    const css = new Blob([text], {type: 'text/css'})
    style.href = window.URL.createObjectURL(css)
    style.type = 'text/css'
    style.rel = 'stylesheet'
    head.append(style)
}

fetch('/style.scss').then(res => res.text()).then(sass => {
  Sass.compile(sass, ({text}) => loadCSS(text))
})   

Now you could swap out Sass.compile for any kind of transformation function you like.

Blob urls keeps your DOM structure clean this way.

I'm sure by now you have your answers, so this is just one more thing you can do with it.

Gossipy answered 10/11, 2022 at 0:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.