-1

Im trying to do a file upload function to IPFS that returns the string of the url for where the file is located. But I cannot get it to return it. I have tried using var and window to declare the variable but it always returns undefined.Also defined the enlace outside of the function but still it always declare undefined. Its like its not updating the value outside of the function. As the console log after it does print the url. (and yes I know there is some trash code, I have been trying to debug the problem)

    function upload() {
      const reader = new FileReader();
      reader.onloadend = function() {
        const ipfs = window.IpfsApi('localhost', 5001) // Connect to IPFS
        const buf = buffer.Buffer(reader.result) // Convert data into buffer
        ipfs.files.add(buf, (err, result) => { // Upload buffer to IPFS
          if(err) {
            console.error(err)
            return
          }
          window.enlace = `http://127.0.0.1:8080/ipfs/${result[0].hash}`
          console.log(`Url --> ${enlace}`)
          console.log(typeof enlace)
          //document.getElementById("url").innerHTML= url
          //document.getElementById("url").href= url
          //document.getElementById("output").src = url
        })
      }
      const photo = document.getElementById("photo");
      reader.readAsArrayBuffer(photo.files[0]); // Read Provided File
      return window.enlace;

    }
Pablo Arriola
  • 334
  • 3
  • 15

1 Answers1

0

I believe ipfs.add is asynchronous, which means return window.enlace executes before window.enlace is set inside of your callback funcion.

lidel
  • 525
  • 3
  • 7