Skip to content

Instantly share code, notes, and snippets.

@pankajpatel
Created October 9, 2017 08:49
Show Gist options
  • Save pankajpatel/d338d703c7de83262f7859e642f85e2d to your computer and use it in GitHub Desktop.
Save pankajpatel/d338d703c7de83262f7859e642f85e2d to your computer and use it in GitHub Desktop.
const generatePreviewData = (file, callback) => {
const fr = new FileReader();
fr.addEventListener('load', (e) => {
if(callback && typeof callback === 'function') callback(fr.result);
});
fr.readAsDataURL(file);
}
const generatePreviewData = (file) => {
const fr = new FileReader();
return new Promise((resolve, reject) => {
fr.addEventListener('load', (e) => {
resolve(fr.result);
});
fr.addEventListener('error', (e) => {
reject();
});
fr.readAsDataURL(file);
});
}
// Import the generatePreviewData function as following ways:
// const generatePreviewData = require('./preview-file');
// or <script src="./preview-file.js"></script>
// OR copy and paste above function in the same file of usage
const photo = document.querySelector('#photo');
generatePreviewData(photo.files[0], (data) => {
const img = document.createElement('img');
img.src = data;
img.height = 200;
document.body.appendChild(img)
})
// Import the generatePreviewData function as following ways:
// const generatePreviewData = require('./preview-file');
// or <script src="./preview-file.js"></script>
// OR copy and paste above function in the same file of usage
const photo = document.querySelector('#photo');
generatePreviewData(photo.files[0])
.then((data) => {
const img = document.createElement('img');
img.src = data;
img.height = 200;
document.body.appendChild(img)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment