Skip to content

Instantly share code, notes, and snippets.

@harlantwood
Last active July 18, 2021 08:09
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harlantwood/58990ebe47b54e05020a13a45a124dff to your computer and use it in GitHub Desktop.
Save harlantwood/58990ebe47b54e05020a13a45a124dff to your computer and use it in GitHub Desktop.
Upload a binary file to IPFS via React.
// 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>
)
}
}
{
"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