Ad

How To Reuse Argument From A Function?

- 1 answer

I have a function that shows image after input(type=file) loads. I need to save the source attribute of image, so I could use it furthermore. This is the code:

 function readURL(input, callback) {
  if (input.files && input.files[0]) {
    let reader = new FileReader();

    reader.onload = function (e) {
      regForm.img.setAttribute('src', e.target.result); // I need to save this somehow, to use it later in a POST Request body.
     }
     reader.readAsDataURL(input.files[0]);
  }
}
Ad

Answer

You can use promise like this:

function readURL(input) {
    return new Promise((resolve) => {
        if (input.files && input.files[0]) {
            let reader = new FileReader()
            reader.onload = function (e) {
                regForm.img.setAttribute('src', e.target.result)
                reolve(e.target.result)
            }
            reader.readAsDataURL(input.files[0])
        }
    })
}

Whenever you want the source const src = await readURL(YOUR FILE)

Ad
source: stackoverflow.com
Ad