forked from fiatjaf/ipfs-dropzone
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
75 lines (66 loc) · 1.78 KB
/
index.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
const IPFS = require('ipfs')
const toBuffer = require('blob-to-buffer')
const Dropzone = require('dropzone')
class IPFSDropzone extends Dropzone {
constructor (el, options) {
options.url = 'https://ipfs.io/' // just to bypass the check.
super(el, options)
this.node = null
this.ipfsRepoName = options.ipfsRepoName || 'ipfs-dropzone'
this.ipfsPath = typeof options.ipfsPath === 'function'
? options.ipfsPath
: file => file.name
}
uploadFiles (files) {
if (this.node === null) {
this.node = new Promise((resolve) => {
let node = new IPFS({ repo: this.ipfsRepoName })
node.once('ready', () => {
resolve(node)
})
})
}
for (let file of files) {
this.emit('sending', file)
}
Promise.all([
this.node,
files,
Promise.all(
files.map(f =>
new Promise((resolve, reject) => {
toBuffer(f, (err, buf) => {
if (err) return reject(err)
resolve(buf)
})
})
)
)
])
.then(([node, files, buffers]) => {
for (let i = 0; i < files.length; i++) {
let buf = buffers[i]
let file = files[i]
node.files.add({
path: this.options.ipfsPath(file),
content: buf
}, {
progress: loaded => {
this._updateFilesUploadProgress([file], null, {
loaded: loaded,
total: file.size
})
}
}, (err, res) => {
file.ipfs = res
if (err) {
this._errorProcessing([file], `ipfs add error: ${err}`)
return
}
this._finished([file])
})
}
})
}
}
module.exports = IPFSDropzone