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

yeh*_*rek 4 javascript node.js ipfs

我想使用 (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)
        })
Run Code Online (Sandbox Code Playgroud)

但它给了我这个错误。fs Add 在浏览器上不起作用

我需要使用 javascript 将一个目录上传到 ipfs,但我找到的所有资源只上传一个文件。或者很多带有哈希值数组的文件。我需要一种方法来上传目录中的所有文件并仅使用一个哈希值来获取文件。提前致谢。

Dav*_*ias 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)
    })
}
Run Code Online (Sandbox Code Playgroud)


wos*_*oss 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,
    })
  }
Run Code Online (Sandbox Code Playgroud)