Skip to content

Instantly share code, notes, and snippets.

@TALlama
Forked from UserAd/image_preview.js
Created August 24, 2010 06:33
Show Gist options
  • Save TALlama/547066 to your computer and use it in GitHub Desktop.
Save TALlama/547066 to your computer and use it in GitHub Desktop.
<input type='file' id='picker'>
<img style='border: 1px solid black' id='img'>
<script>
var onFilePicked = function(el, callback, opts) {
opts = opts || {}
var delayedCallback = function(url) {
setTimeout(function() {callback(url)}, 0);
}
el.onchange = el.onmouseout = function(event) {
if (typeof(FileReader)!='undefined') {
//HTML5 FileAPI
var reader = new FileReader();
reader.onload = function(e){
delayedCallback(e.target.result);
}
reader.readAsDataURL(el.files.item(0));
} else if (el.files && el.files.item(0).getAsDataURL) {
// Firefox 3.0-3.6
var dataurl = el.files.item(0).getAsDataURL();
delayedCallback(dataurl);
} else if (el.files && !el.files.item(0).getAsDataURL) {
//Safari and webkit not supported now
//FIXME is there a way to support Safari?
callback(null)
} else {
//IE!!!!
//FIXME won't work if the site is hosted outside the Trusted Zone
delayedCallback(el.value);
}
}
};
onFilePicked(document.getElementById('picker'), function(url) {
document.getElementById('img').src = url;
})
</script>
@TALlama
Copy link
Author

TALlama commented Aug 24, 2010

Generalized the method so that the client code can just say "give me a new URL when one is chosen" and it'll just work.

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