Image Base64 Converter
I need a bootstrap (v4) based image (file) upload component that allows a user to upload an image and converts the contents of the file to a Base64 string.
by brady houseknecht
September 29, 2018
HTML
<script src="https://unpkg.com/[email protected] /dist/jquery.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/[email protected] /dist/sketchy/bootstrap.min.css">
<br><br>
<div class="d-flex w-100 h-100 justify-content-center align-items-center">
<div class="jumbotron w-50 h-100" >
<h2>Image Base64 Converter</h2>
<table width="100%">
<tr>
<td>
<label for="imageUpload">Upload an Image:</label>
<input type="file" class="form-control-file border" id="imageUpload" accept=".png,.jpg" aria-describedby="fileHelp"> </td>
</tr>
<tr>
<td>
<img id="uploadedImg" width="150px">
</td>
</tr>
<tr>
<td>
<div class="form-group">
<label for="imgString">Base64 String:</label>
<textarea class="form-control" rows="5" id="imgString"></textarea>
</div>
</td>
</tr>
</table>
</div>
</div>
<script>
document.write('<a id="githubLink" target="_blank" href="https://github.com/bradyhouse/house/tree/master/fiddles/jquery/fiddle-0067-Bootstrap4ImageUpload"' +
'><img style="z-index: 1000; position: absolute; top: 0; right: 0; border: 0;" ' +
'src="https://camo.githubusercontent.com/652c5b9acfaddf3a9c326fa6bde407b87f7be0f4/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6f72616e67655f6666373630302e706e67" ' +
'alt="Fork me on GitHub"><\/a>');
</script>
JavaScript
(function (app, $, undefined) {
"use strict";
app.view = app.view || {
renderImage: function (files, imgCtrl) {
for (var i = 0; i < files.length; i++) {
let file = files[i],
reader = new FileReader();
reader.onload = (function (aImg) {
return function (e) {
aImg.src = e.target.result;
};
})(imgCtrl);
reader.readAsDataURL(file);
}
},
renderTxt: function (files, txtCtrl) {
for (var i = 0; i < files.length; i++) {
let file = files[i],
reader = new FileReader();
reader.onload = (function (txt) {
return function (e) {
txt.value = e.target.result;
};
})(txtCtrl);
reader.readAsDataURL(file);
}
}
};
$(document).ready(function () {
$('#imageUpload').change(function () {
let files = $('#imageUpload').prop('files'),
imgCtrl = document.getElementById('uploadedImg'),
txtCtrl = document.getElementById('imgString');
if (imgCtrl && files && files.length) {
app.view.renderImage(files, imgCtrl);
if (txtCtrl) {
app.view.renderTxt(files, txtCtrl);
}
}
});
});
})(window.app = window.app || {}, jQuery);