Skip to content

Instantly share code, notes, and snippets.

@RohitBittu
Created July 12, 2018 06:28
Show Gist options
  • Save RohitBittu/9303cc949d5849c763ff8696e4388144 to your computer and use it in GitHub Desktop.
Save RohitBittu/9303cc949d5849c763ff8696e4388144 to your computer and use it in GitHub Desktop.
File API demo
<section>
<img src="http://www.randomlengthsnews.com/wp-content/themes/gonzo/images/no-image-blog-one.png" id="img">
<a id="addphoto" href="#" class="btn">+ Add Photo</a>
<a id="removephoto" href="#" class="btn">x Remove Photo</a>
</section>
<input type="file" name="file" id="file" accept="image/*;capture=camera" capture="camera" />
var img = document.getElementById('img');
var noimage = img.src;
function handleFileSelect(evt) {
var file = evt.target.files[0]; // FileList object, files[0] is your file
console.log(file);
img.src = window.URL.createObjectURL(file);
}
document.getElementById('file').addEventListener('change', handleFileSelect, false);
document.querySelector('#removephoto').addEventListener('click', function(e) {
document.getElementById('file').value="";
img.src=noimage;
e.preventDefault();
});
document.querySelector('#img').addEventListener('click', function(e) {
performClick(document.getElementById('file'));
e.preventDefault();
}); document.querySelector('#addphoto').addEventListener('click', function(e) {
performClick(document.getElementById('file'));
e.preventDefault();
});
function performClick(node) {
var evt = document.createEvent("MouseEvents");
evt.initEvent("click", true, false);
node.dispatchEvent(evt);
}
section{width:300px;margin:0 auto;}
#img{max-height:300px;max-width:300px;}
.btn{
background-color:#333;
display:block;color:#fff;
padding:10px 15px;
font: 16px Helvetica;
text-decoration:none;
text-align:center;
margin:1px 0;
}
#file{display:none;}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment