Created
August 13, 2018 01:51
-
-
Save 0xCourtney/138b97c0079c4b095ea9e0cbf488564e to your computer and use it in GitHub Desktop.
Uploads file to IPFS via Infura
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Note this only shows the function being called in the parent component. The child component | |
// passes the event and contract address to the parent... I can make this more complete if requested... | |
uploadFile = async (event, contractAddress) => { | |
event.stopPropagation(); | |
event.preventDefault(); | |
const { web3, accounts } = this.state; | |
const file = event.target.files[0]; | |
let reader = new window.FileReader(); | |
reader.readAsArrayBuffer(file); | |
reader.onloadend = async () => { | |
const buffer = await Buffer.from(reader.result); | |
const ipfsHash = await ipfsUpload(buffer); | |
const instance = await getContractInstance( | |
web3, | |
BountyContract, | |
bountyAddress | |
); | |
console.log(ipfsHash); | |
instance.methods.submitChallenge(ipfsHash).send({ from: accounts[0] }); | |
}; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ipfsAPI from 'ipfs-api'; | |
const ipfs = new ipfsAPI({ | |
host: 'ipfs.infura.io', | |
port: 5001, | |
protocol: 'https' | |
}); | |
export function ipfsUpload(buffer) { | |
return new Promise(function(resolve, reject) { | |
ipfs.add(buffer, (err, ipfsHash) => { | |
if (err) { | |
console.log(err); | |
reject(err); | |
} else { | |
const hash = ipfsHash[0].hash; | |
let res = `"https://gateway.ipfs.io/ipfs/${hash}"`; | |
resolve(res); | |
} | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment