I want to upload an image from a file browser dialog .I want the image to be previewed as the user selects the image.It is working in jsfiddle but it isn't working in my project .
The error is
"Uncaught TypeError: Cannot read property 'addEventListener' of null"
I don't know how to solve it. Please help me?
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/>'
].join('');
document.getElementById('previewImg').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
.thumb {
border: 1px solid #000000;
height: 75px;
margin: 10px 5px 0 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='file' id="files" name="image" multiple="multiple" />
<div id='previewImg'></div>