使用ipfs (js-ipfs-http-client)上传完整目录到IPFS

4
我想使用(js-ipfs-http-client)模块在我的浏览器上上传一个目录到ipfs。我找到了这个旧问题。 https://github.com/ipfs/js-ipfs/issues/277 所以我决定使用递归方式添加文件并仅获取一个哈希。
ipfs.addFromFs('path', { recursive: true, ignore: ['subfolder/to/ignore/**'] }, (err, result) => {
            if (err) { throw err }
            console.log(result)
        })

但它给了我这个错误。 fs Add doesn't work on browser

我需要使用JavaScript将一个目录上传到IPFS,但我找到的所有资源都只上传一个文件。或者上传一堆文件并获得哈希数组。我需要一种方法来上传目录中的所有文件,并只获取一个哈希值。提前谢谢。

2个回答

6

Yehia,我相信你正在寻找的答案在 https://github.com/ipfs/js-ipfs-http-client/blob/master/examples/upload-file-via-browser/src/App.js#L29-L67

// Example #1
// Add file to IPFS and return a CID
saveToIpfs (files) {
  let ipfsId
  this.ipfs.add([...files], { progress: (prog) => console.log(`received: ${prog}`) })
    .then((response) => {
      console.log(response)
      ipfsId = response[0].hash
      console.log(ipfsId)
      this.setState({ added_file_hash: ipfsId })
    }).catch((err) => {
      console.error(err)
    })
}

// Example #2
// Add file to IPFS and wrap it in a directory to keep the original filename
saveToIpfsWithFilename (files) {
  const file = [...files][0]
  let ipfsId
  const fileDetails = {
    path: file.name,
    content: file
  }
  const options = {
    wrapWithDirectory: true,
    progress: (prog) => console.log(`received: ${prog}`)
  }
  this.ipfs.add(fileDetails, options)
    .then((response) => {
      console.log(response)
      // CID of wrapping directory is returned last
      ipfsId = response[response.length - 1].hash
      console.log(ipfsId)
      this.setState({ added_file_hash: ipfsId })
    }).catch((err) => {
      console.error(err)
    })
}

最好将代码复制到答案中,因为Github的内容可能会更改。 - Andrii Muzalevskyi

5

我建议使用addAll方法

以下是示例:

  const addedFiles: AddedFiles[] = []
  for await (const file of ipfsClient.addAll(
    globSource(path, '**/*', {
      hidden: true,
    }),
    { ...ipfsOptions, fileImportConcurrency: 50 }
  )) {
    addedFiles.push({
      cid: file.cid.toString(),
      path: file.path,
      size: file.size,
    })
  }

谢谢,兄弟,这正是我所需要的。 - Chiano

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接