Some time ago i needed to be able to seek to any point in a <video>, and i had to do this across 10-30 videos at the same time, all the time. Streaming the videos from a remote server made most browsers buffer a few seconds forward, but not backwards, and loading them from a server without streaming support allowed forward playback only; no seeking at all!

Seeking in the video without having to re-buffer from server was essential, and so the quest for a solution began (okay, a very short 60 minute-ish quest, but a quest, nonetheless!).

§BlobFetch.js

And so i created BlobFetch.

BlobFetch is a tiny library for fetching (large) objects as blobs. When downloaded, you can save with LocalFileSystem or use it directly with URL.createObjectURL.

Some highlights are:

  • progress callbacks (well, dah)
  • abort download
  • MIME type assertion (fire error instead of success callback if you expected video/mp4 but got application/json)

§Example

Type any URL and press download.

Note that a correct Access-Control-Allow-Origin header is needed.

imgur sends correct headers, so head over there and find a large test image.

A few urls you could try:

  • http://i.imgur.com/RW5QXyX.jpg
  • http://vjs.zencdn.net/v/oceans.mp4 ( from videojs.com )
  • blobfetch.js
Download


§Download

You can get the full source over at github: gist.github.com/tudborg/6846380

§Usage

§Simple usage

Here we download a video, create an object URL and set it as the source of a video element.

1var bf = BlobFetch('http://vjs.zencdn.net/v/oceans.mp4', function () {
2    videoElement.src = window.URL.createObjectURL(this.response);
3});

§Getting progress

 1var bf = BlobFetch({
 2    url: 'http://vjs.zencdn.net/v/oceans.mp4',
 3    success: function () {
 4        myVideo.src = window.URL.createObjectURL(this.response);
 5    },
 6    progress: function () {
 7        //progress is a number between 0 and 1
 8        console.log((this.progress*100)+'% complete');
 9    }
10});

§Abort a download

 1var bf = BlobFetch({
 2    url: 'http://vjs.zencdn.net/v/oceans.mp4',
 3    progress: function () {
 4        console.log((this.progress*100)+'% complete');
 5    },
 6    //the abort callback will be fired if someone aborts the download
 7    abort: function () {
 8        console.warn("You aborted the download!!");
 9    }
10});
11
12//calling abort is as simple as
13bf.abort();

§All of it

 1var bf = BlobFetch({
 2    url: 'http://vjs.zencdn.net/v/oceans.mp4',
 3    //MIME check. Error called if download does not match
 4    expect: 'video/mp4',
 5    success: function () {
 6        myVideo.src = window.URL.createObjectURL(this.response);
 7    },
 8    error: function (err) {
 9        throw err;
10    },
11    progress: function () {
12        console.log((this.progress*100)+'% complete');
13    },
14    abort: function () {
15        console.warn("You aborted the download!!");
16    }
17});

You can check the source of this page for an actual usage example.