简体   繁体   中英

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM