2

I want to make a upload image and preview, want to make all selected images to base64 and create an array from it, but after onload and array.push array return empty, any idea what's wrong? I'm using this code in reactjs but for demo to share you I managed to use jQuery

function handleImage(e) {
  let image = e.target.files;
  let result = [...image];
  let array = [];

  result && result.map(function(img, i) {
    let fileReader = new FileReader();
    fileReader.readAsDataURL(img);
    fileReader.onload = () => {
      array.push(fileReader.result);
    }
  })
  console.log(array) // return empty!
}

$('input[type="file"]').change(function(e) {
  handleImage(e)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" onChange="handleImage" />
Jack The Baker
  • 1,781
  • 1
  • 20
  • 51
  • It's normal, you are calling an asynchronous function. Look at this post : https://stackoverflow.com/questions/9815625/looping-through-files-for-filereader-output-always-contains-last-value-from-loo – jean-max Feb 05 '22 at 11:22

0 Answers0