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

211
Views
Convert each image input to DataUrl or Base64 image while iterating
var toPush = []
for(var i = 1; i <= myVariable; i++){
     var variable1 = document.getElementById('q' + i).value;
     var var2 = document.getElementById(i + 'x').value;
     var var3 = document.getElementById(i + 'y').value;
     var var4 = document.getElementById(i + 'z').value;
     var var5 = document.getElementById(i + 'd1').value;
     var var6 = document.getElementById('xy' + i).value;
     var file = document.getElementById("fileup" + i);
     var twofour = [var2, var3, var4, var5];
                    
     let reader = new FileReader();
        reader.readAsDataURL(file.files[0]);

        reader.onload = function () {
           pictureURL = reader.result;
        };
        reader.onerror = function (error) {
           console.log('Error: ', error);
        };
     toPush.push({"variable1": variable1, "twofour": twofour, "pictureURL": pictureURL} 
}

The application can add X many inputs by appending them do div. When it comes to pushing the data, I want to have the file input, which is the only image input, be read as DataURL, so it can show be used as a source to an image preview. I don't know if it is because of the iteration, but the pictureURL variable pushes as empty: in the database I got "pictureURL": "".

Is there any way around it?

Thank you in advance.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

There are multiple issues with this code. The reason that you're not receiving the pictureUrl is because you're reading it before it's ready.

FileReader reads the file asynchronously. It provides us a callback onload that is executed when it has read the file. We get the content of the file as reader.result only when this callback is executed. You have to rewrite your code to process the content of the file when it's either FileReader.onload or FileReader.onerror are executed.

See the working example below. I have removed unnecessary code. You can run the code by clicking on Run code snippet button at the bottom of the post

function showIcons() {

    let files = document.querySelector('#files').files;

    if(files.length) {
        document.querySelector('#show-icons-error').textContent = "";
    } else {
        document.querySelector('#show-icons-error').textContent = 'No files have been selected';
    }

    let imageIcons = document.querySelector('#image-icons');
    imageIcons.innerHTML = '';

    let imageUrlArr = [];

    for(var i = 0; i < files.length; i++) {
        let imageIconHolder = document.createElement('img');
        imageIconHolder.classList.add('image-icon');
        imageIconHolder.setAttribute('image-index', i);

        imageIcons.appendChild(imageIconHolder);

        let file = files[i];

        let reader = new FileReader();
        reader.readAsDataURL(file);

        reader.onload = function () {
            pictureURL = reader.result;
            imageIconHolder.src = pictureURL;
            
            imageUrlArr[i] = pictureURL;//Setting ith image, not pushing.
        };
        
        reader.onerror = function (error) {
            console.log(`Error loading image at index : ${i}, error: ${error}`);

            imageUrlArr[i] = error;//Error for ith image
        };
    }
}
.image-icon {
    width: 10em;
    display: block;
    min-height: 5em;
}
<html>
    <body>
        <label for="files" class="btn">Select Images</label>
        <input id="files" type="file" value="Select File" accept="image/*" multiple="multiple">
        <br/>
        <br/>
        <div>
            <button id="show-icons" onclick="showIcons()">Show Icons</button>
            <span id='show-icons-error' style="color: red; font-weight: bold;"></span>
        </div>
        <br/>
        <div id="image-icons">
            
        </div>
    </body>
</html>

about 4 years ago · Juan Pablo Isaza 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!