1

I am working on a dapp and wish to upload a file on ipfs and retrieve its hash to be used further. The concerned code is as follows

const ipfsClient = require(‘ipfs-http-client’)

const ipfs = ipfsClient({ host: ‘ipfs.infura.io’, port: 5001, protocol: ‘https’ })

captureFile = event => {

    event.preventDefault()

    const file = event.target.files[0]

    const reader = new window.FileReader()

    reader.readAsArrayBuffer(file)

    

    reader.onloadend = () => {

      this.setState({ buffer: Buffer(reader.result) })

      console.log('buffer', this.state.buffer)

    }
}

uploadAsset = (cost) => {

console.log("Submitting file to ipfs...")

ipfs.add( this.state.buffer, (error, result) => { //Execution stops here

  console.log('Ipfs result', result)

  if(error) {

    console.log("Error")  

    console.error(error)

    return

  }

console.log("no error")  

  this.setState({ loading: true })

  this.state.dstock.methods.uploadAsset(result[0].hash, cost).send({ from: this.state.account }).on('transactionHash', (hash) => {

    this.setState({ loading: false })

  })

})

The output is as given below. The code isn't returning the result.

enter image description here

1 Answer 1

0

I know this response might be a bit late but until just a moment ago I was experiencing the same problem as you. However, I managed to find a solution! Even if you've also managed to get this to work, I'll share how I fixed this for posterity.

The reason ipfs.add seems to just not work is that it needs to be part of an async/await function. If it isn't, it just seems not to execute. Here's what my code is like; it's not identical to yours but it's pretty similar and should hopefully give you a good idea of how this should work.

const [ipfsHash, setIpfsHash] = useState("");
const [isFile, setFile] = useState(null);
const [buffer, setBuffer] = useState(null);

const captureFile = (event) => {
    if (event.target.files[0]) {
        event.preventDefault();
        setFile(URL.createObjectURL(event.target.files[0]));
        
        const reader = new FileReader();
        reader.readAsArrayBuffer(event.target.files[0])
        reader.addEventListener("load", () => {
                setBuffer(reader.result)
        })
    }
}

useEffect(() => {
    if (buffer) {
        getHash()
    }
});

async function getHash() {
    
    try {
        const uploadResult = await ipfs.add(Buffer.from(buffer))
        setIpfsHash(uploadResult.path)
    } catch(e) {
        console.log(e)
        toast.error(e.message)
        return
    }
}

I hope this helps! I feel like this should be better documented.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.