Last active
July 18, 2021 08:09
-
-
Save harlantwood/58990ebe47b54e05020a13a45a124dff to your computer and use it in GitHub Desktop.
Upload a binary file to IPFS via React.
This file contains 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
// This is DEPRECATED, see a full running example here instead: | |
// https://github.com/ipfs/js-ipfs-api/tree/97f6ed27d72b189c02865cb0fdd4f58fafd89625/examples/upload-file-via-browser | |
import React from 'react' | |
import IpfsApi from 'ipfs-api' | |
const Buffer = require('buffer/').Buffer | |
export default class AddMedia extends React.Component { | |
constructor { | |
config = {} // set to your IPFS host, port, etc | |
this.ipfsApi = IpfsApi(config) | |
} | |
captureFile = (event) => { | |
event.stopPropagation() | |
event.preventDefault() | |
const file = event.target.files[0] | |
let reader = new FileReader() | |
reader.onloadend = () => this.saveToIpfs(reader) | |
reader.readAsArrayBuffer(file) | |
} | |
saveToIpfs = (reader) => { | |
// console.log(this.arrayBufferToString(reader.result)) | |
let ipfsId | |
const buffer = Buffer.from(reader.result) | |
this.ipfsApi.add(buffer) | |
.then((response) => { | |
ipfsId = response[0].Hash | |
console.log(ipfsId) | |
}) | |
} | |
arrayBufferToString = (arrayBuffer) => { | |
return String.fromCharCode.apply(null, new Uint16Array(arrayBuffer)) | |
} | |
handleSubmit = (event) => { | |
event.preventDefault() | |
} | |
render () { | |
return ( | |
<form id="captureMedia" onSubmit={this.handleSubmit}> | |
<input type="file" onChange={this.captureFile} /> | |
</form> | |
) | |
} | |
} |
This file contains 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
{ | |
"dependencies": { | |
"buffer": "4.7.0", | |
"ipfs-api": "4.1.1", | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A full running example: https://github.com/ipfs/js-ipfs-api/tree/97f6ed27d72b189c02865cb0fdd4f58fafd89625/examples/upload-file-via-browser