URL.createObjectURL()
is part of the URL-interface, which can be used to construct and parse URLs. URL.createObjectURL()
specifically, can be used to create a reference to a File
or a Blob
. As opposed to a base64-encoded data URL, it doesn’t contain the actual data of the object – instead it holds a reference.
Let’s say you have a page that prompts the user to upload an image. The file input element is, as we all know, very simple and far from user friendly. When a user has selected an image, it would make sense (in a lot of cases) to show a preview of the image. We are now finally able to solve this problem in a simple and intuitive way:
1 2 3 4 5 6 7 8 9 | [code language="js"] var fileInput = document.querySelector('input[type="file"]'); var preview = document.getElementById('preview'); fileInput.addEventListener('change', function(e) { var url = URL.createObjectURL(e.target.files[0]); preview.setAttribute('src', url); }); [/code] |
Simple, right? This produces something like the following:
The nice thing about this is that it’s really fast. Previously, we’ve had to instantiate a FileReader
instance and read the whole file as a base64 data URL, which takes time and a lot of memory. With createObjectURL()
, the result is available straight away, allowing us to do things like reading image data to a canvas or the length of an audio file. Great, right?
One thing to keep in mind is that once you’re done with the generated object URL, you should revoke it. This frees up memory, which is usually handled automatically when you close the page or navigate away from it, but it’s generally a good idea anyway. Revoking the URL is a simple process – just call URL.revokeObjectURL(<objectUrl>)
from the onLoad
-handler of the element you are using it for.
Read more about createObjectUrl on the Mozilla Developer Network.