Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
JS switch what form returns to a b64 string

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])?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

  • Use the input value property
  • Don't use inline on* JS handlers (same as hopefully you don't use inline style attributes). Use addEventListener() instead
  • Add a missing Form's action attribute for the URL you're sobmitting to
  • Add a required attribute to your Input Element

const 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>

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!