I want to save an image in b64 format in my database. For reasons I want to deal with the logic on the frontend side of things. My backend sends a form and already encapsulates the filefield input with a onChange function that converts img -> b64:
<form>
<input id="file-select" name="pic" class="form-control" type="file" onchange="getImage()">
<button>submit</button>
</form>
where getImage() looks like this:
function getImage() {
var reader = new FileReader();
var f = document.getElementById("file-select").files;
reader.onloadend = function () {
console.log(reader.result);
}
reader.readAsDataURL(f[0]);
}
How can I replace what the input field submits on button press with the value of reader.readAsDataURL(f[0])?
value propertyon* JS handlers (same as hopefully you don't use inline style attributes). Use addEventListener() insteadaction attribute for the URL you're sobmitting torequired attribute to your Input Elementconst EL = (sel, el) => (el || document).querySelector(sel);
const EL_file = EL("#file-select");
const readFile = () => {
if (!EL_file.files) return;
const FR = new FileReader();
FR.addEventListener("load", (evt) => EL_file.value = evt.target.result);
FR.readAsDataURL(this.files[0]);
};
EL_file.addEventListener("change", readFile);
<form id="file-form" action="save_base64.php">
<input id="file-select" name="pic" class="form-control" type="file" required>
<button>Submit</button>
</form>