This repository was archived by the owner on Mar 10, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 297
/
Copy pathApp.js
94 lines (86 loc) · 2.31 KB
/
App.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/* eslint-disable no-console */
'use strict'
const React = require('react')
const ipfsClient = require('ipfs-http-client')
class App extends React.Component {
constructor () {
super()
this.state = {
added_file_hash: null
}
this.ipfs = ipfsClient('/ip4/127.0.0.1/tcp/5001')
// bind methods
this.captureFile = this.captureFile.bind(this)
this.saveToIpfs = this.saveToIpfs.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
captureFile (event) {
event.stopPropagation()
event.preventDefault()
if (document.getElementById('keepFilename').checked) {
this.saveToIpfsWithFilename(event.target.files)
} else {
this.saveToIpfs(event.target.files)
}
}
// Example #1
// Add file to IPFS and return a CID
async saveToIpfs (files) {
const source = this.ipfs.add(
[...files],
{
progress: (prog) => console.log(`received: ${prog}`)
}
)
try {
for await (const file of source) {
console.log(file)
this.setState({ added_file_hash: file.path })
}
} catch (err) {
console.error(err)
}
}
// Example #2
// Add file to IPFS and wrap it in a directory to keep the original filename
async saveToIpfsWithFilename (files) {
const file = [...files][0]
const fileDetails = {
path: file.name,
content: file
}
const options = {
wrapWithDirectory: true,
progress: (prog) => console.log(`received: ${prog}`)
}
const source = this.ipfs.add(fileDetails, options)
try {
for await (const file of source) {
console.log(file)
this.setState({ added_file_hash: file.cid.toString() })
}
} catch (err) {
console.error(err)
}
}
handleSubmit (event) {
event.preventDefault()
}
render () {
return (
<div>
<form id='captureMedia' onSubmit={this.handleSubmit}>
<input type='file' onChange={this.captureFile} /><br/>
<label htmlFor='keepFilename'><input type='checkbox' id='keepFilename' name='keepFilename' /> keep filename</label>
</form>
<div>
<a target='_blank'
href={'https://ipfs.io/ipfs/' + this.state.added_file_hash}>
{this.state.added_file_hash}
</a>
</div>
</div>
)
}
}
module.exports = App