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.
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.
Hey there, I’m having an issue with “Content Security Policy” when I use this method, any chance you could help me out?
Hi Calvin! From what I could find out you may need to configure Content-Security-Policy on the server: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/object-src
Do you get the Content Security Policy for any image or just for a specific one?