🎁 Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

Using URL.createObjectURL() to create uploaded image previews in Javascript

While working on the example for the image object detection with TensorJs I needed a way to preview the upload of an image.

After some research, I found that one of the easiest ways is to use the URL.createObjectURL() method.

What it does is to get as a parameter a given object, in our case the uploaded image, and return a string containing the URL for the blob data object of that image.

The blob data object will be kept in the document memory space until the document is unloaded or the URL is explicitly released.

So, if we have the below markup:

<input id="inp" type='file' accept='image/*' capture='camera'/>

And this Javascript:

const input = document.querySelector('#inp')

input.addEventListener('change', () => {
  const url = window.URL.createObjectURL(input.files[0])
  console.log(url)
}) 🌼

When we select an image, the url output will be similar to the one below:

blob:https://cdpn.io/75e3de17-c6e5-48ae-acc5-88dbec499649

We can even navigate to that URL and see the actual image.

And the nice part is that we can easily take this URL and set it as the src of an image element.

Finally, just add a link with the download attribute if we want to have the option to download that file.

Using URL.createObjectURL() to create uploaded image previews in Javascript code logic

The Javascript will make sure to putΒ the url variable as the href for the download link plus the src for the image:

const input = document.querySelector('#inp')
const link = document.querySelector('#dwn')
const img = document.querySelector('#img')

input.addEventListener('change', () => {
  const url = window.URL.createObjectURL(input.files[0])
  img.src = url
  console.log(url)
  link.setAttribute( "href", url )
})

You can check out the full working codepen here.

As a final note keep in mind that when we create Object URLs, the browser will keep them in memory until the document is unloaded (the browser window is closed) or until the URL is explicitly released.

We can manually unload the created blob data object by using:

URL.revokeObjectURL(objectURL)

If you want to learn more try to make a more complex example where you upload multiple images with React and generate their previews.

πŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

πŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


2 Replies

Leave a Reply

Your email address will not be published. Required fields are marked *