Skip to content

Instantly share code, notes, and snippets.

@stela5
Created November 15, 2011 04:32
Show Gist options
  • Save stela5/1366150 to your computer and use it in GitHub Desktop.
Save stela5/1366150 to your computer and use it in GitHub Desktop.
File API example (loading client images into browser without using a server)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=720,minimum-scale=1.0">
<title>File &amp; FileReader API</title>
<style>#input{display:none;}</style>
</head>
<body>
<p id="status">File &amp; FileReader API not supported</p>
<p id="input"><input type=file></p>
<div id="holder"></div>
<script>
var state = document.getElementById('status');
var upload = document.getElementsByTagName('input')[0];
var holder = document.getElementById('holder');
if (typeof window.FileReader !== 'undefined') {
state.innerHTML = 'File & FileReader API supported';
document.getElementById('input').style.display = 'block';
}
upload.onchange = function(e) {
e.preventDefault(); // prevent navigation to "#"
var file = upload.files[0];
var ext = file.name.match(/\.([^\.]+)$/);
var valid = {"png":1,"jpg":1,"jpeg":1,"gif":1,"bmp":1,"ico":1};
if (ext && (ext.length > 1) && ext[1].toLowerCase() in valid) {
var reader = new FileReader();
reader.onload = function(event) {
if(/\bdata:image.*?base64/i.test(event.target.result)) { // double-check event.target.result = data:image/[ext];base64,...
var img = new Image();
img.onload = function() {
var w = (window.innerWidth) ? (window.innerWidth * 0.975) : 720;
if (img.width > w) {
img.width = w; // resize image to fit in browser window
}
holder.innerHTML = '';
holder.appendChild(img);
};
img.src = event.target.result;
}
};
reader.readAsDataURL(file);
} else {
holder.innerHTML = 'Invalid image';
}
return false;
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment