Using URL.createObjectURL()

This is a blog post about using the Web API URL.createObjectURL(). Here we will go through the use cases as well as the inner intricacies of what this Web API does. First up lets see how to use the API.

URL.createObjectURL() #

Syntax from MDN: #

objectURL = URL.createObjectURL(blob);

createObjectURL is a static method provided by the URL Web API.

Returns a DOMString containing a unique blob URL, that is a URL with blob: as its scheme, followed by an opaque string uniquely identifying the object in the browser.

So when we invoke the function on the variable blob, we get back a persistent reference string with a unique URL that temporarily references to the in-memory blob object that lives in the Blob URL Store.

It is a persistent reference since as long as that blob is in memory the reference string will be in play unless revoked.

It is temporary however since when the browser is refreshed or basically unloaded, this reference is no longer held since that would be a security concern for sure. The reference is also temporary since it can be revoked using the Web API URL.revokeObjectURL().

It is unique since each time you call createObjectURL(), a new object URL is created, even if you’ve already created one for the same object. These must be individually revoked by calling URL.revokeObjectURL() on each one.

Syntax from MDN: #

window.URL.revokeObjectURL(objectURL);

Calling the revokeObjectURL() static function also lets the browser know that this file is no longer needed and can be released from memory, the blob is also removed from the Blob URL Store immediately. User agents are then free to garbage collect resources removed from the store.

Use Cases #

FileReader #

While at first it might be very similar to that of the FileReader API, createObjectURL provides different paths for your use case rather than doing readAsDataURL.

createObjectURL readAsDataURL
execution synchronous asynchronous
memory pointer base64 payload
caniuse ie10 and above ie10 and above
limit blob limit (varies around 800mb) around 10mb
type object url data uri

The differences really start to matter when dealing with videos or very high quality pictures since passing along a base64 representation of it wouldn’t be practical. It would need to process the data as opposed to using createObjectURL where a pointer is all that is needed to display the uploaded file. For more information check out this lab to try it out.

Upload #

The use case here is similar to the value proposition of File.readAsDataURL where a selected file can be previewed, edited, and deleted before the process of uploading it (with the help of other tools such as Canvas or HTML elements).

// Binded to the input element when event onChange
function onChange(event) {
  const files = event.target.files;
  if (files && files.length > 0) {
    const targetFile = files[0];
    try {
      const objectURL = window.URL.createObjectURL(targetFile);
      mediaElem.src = objectURL;
      window.URL.revokeObjectURL(objectURL);
    }
    catch(e) {
      try {
        // Fallback if createObjectURL is not supported
        const fileReader = new FileReader();
        fileReader.onload = (evt) => {
            mediaElem.src = evt.target.result;
        };
        fileReader.readAsDataURL(targetFile);
      }
      catch(e) {
        console.log(`File Upload not supported: ${e}`);
      }
    }
  }
}

In this case mediaElem is the HTML element that would host the preview media that gets verified or used for augmenting the media.

src #

URL.createObjectURL returns us a nicely packed reference string from the File provided that can be passed along to <img> elements, <video> elements or even <audio> elements in the src property. This allows the user to immediately see what file they have chosen from an <input type="file"/> file picker or from drag and drop functionality since they provide the file that is ingested by the createObjectURL method.

createObjectURL Reference String Example:

"blob:http://svbtle.com/5974d3ca-782b-4fec-9a3e-6aa9690be573"

Compatibility #

The URL.createObjectURL Web API is supported by most modern browsers including IE 10 (exceptions may apply for usage within Web Workers).

http://caniuse.com/#search=createObjectURL

 
429
Kudos
 
429
Kudos

Now read this

Using Angular $compile to Escape Watcher Hell

This is a blog on how to handle repeating directive elements without using the ng-repeat directive when using AngularJS. We’ll keep this blog high level and assume the reader knows Angular development. Sample: <div ng-repeat='spell in... Continue →