Skip to content

Instantly share code, notes, and snippets.

@HaNdTriX
Last active February 18, 2021 20:02
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save HaNdTriX/bdffd11761701fbeba27f23e9a69515f to your computer and use it in GitHub Desktop.
Save HaNdTriX/bdffd11761701fbeba27f23e9a69515f to your computer and use it in GitHub Desktop.
Example of converting a file to a dataURL in ES6
const toDataURL = url => fetch(url)
.then(response => response.blob())
.then(blob => new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onloadend = () => resolve(reader.result)
reader.onerror = reject
reader.readAsDataURL(blob)
}))
@HaNdTriX
Copy link
Author

HaNdTriX commented Mar 29, 2016

Usage

toDataURL('http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png')
  .then(result => console.log(result))
  .catch(error => console.error(error))

Works not only for images 😄

more info

@yairEO
Copy link

yairEO commented Nov 4, 2016

fetch has not so good support and is experimental

@rohmanhm
Copy link

rohmanhm commented Jan 8, 2017

line 8, I think you make a typo.
change to like this

  }));

@Cedric-song
Copy link

@rohmanhm yes!!!

@Booligoosh
Copy link

awesome!

@HaNdTriX
Copy link
Author

HaNdTriX commented Mar 8, 2017

@rohmanhm I have updated the gist. Totally missed that 😳

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment