Using URL.createObjectURL()
https://w3c.github.io/FileAPI/#dfn-createObjectURL

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.

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).

This was originally published at chrisrng.svbtle.com.

Cool post but did you test the API with safari? What about Samsung phones native browsers?

To view or add a comment, sign in

More articles by Chris Ng

  • My hopes for Ember in 2019 – Better JavaScript Community Visibility

    This blog is my input on what I believe the priorities should be for Ember in 2019, in response to the second annual…

    3 Comments
  • ForwardJS Ottawa 2019 Recap

    ForwardJS Ottawa is a 2 day conference held at the Adobe offices in Ottawa, Ontario, Canada. The conference had…

    2 Comments
  • The Open Office Layout

    Let's talk about a contentious topic among developers – the open office layout. While some developers love it, the…

    4 Comments
  • WYSIWYG 3: Browser Peace?

    Hey all, In this week’s issue of WYSIWYG, we’ll be taking a break from the security issues and jumping into browser…

    1 Comment
  • WYSIWYG 2: How do we protect our data?

    Hey all, Fresh off the security breaches from last week’s edition, we have even more data compromises to report. This…

    1 Comment
  • WYSIWYG 1: Security Issues All Around

    Hi there! Welcome to the first edition of WYSIWYG by Chris Ng! WYSIWYG, pronounced "wiz-ee-wig", is an acronym for…

  • Make It Beginner Friendly – My hopes for Ember in 2018

    This blog is in response to Katie Gengler’s Call for Blog Posts with the goal of having shared, clear, and published…

    13 Comments
  • EmberConf 2018 Recap

    EmberConf is the best place to meet the people behind the Javascript framework Ember.js.

  • How to Write About What You're Working On

    Note: While I write this from a software engineer’s point of view, many parts of this article are easily transferable…

    3 Comments
  • Dealing with the Communication Paradox

    TL;DR: Getting to the point with as much detail as needed reduces both problems of lacking in context and information…

Others also viewed

Explore content categories